-->

Wednesday, November 26, 2014

Example of SQL Injection attack

SQL Injection means, Inject the database by the SQL Query, this query executed by the input control like TextBox, URL etc. Suppose we have a table department and we want to retrieve some data from the table by the TextBox. You want to retrieve all the rows, which is related to first department no. Now, you should to enter 1 in the TextBox, then you will get rows, which is related to putted number in the TextBox. If you want to put some number like:

1 or 1=1 then you will get all rows which is available in the table.
If this query is executed it means deletion is also possible with the table.Like
1;Drop table table_name

Source Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="my.aspx.cs" Inherits="my" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
 </head>
<body>
<form id="form1" runat="server">

    Enter Department_No :
    <asp:TextBox ID="TextBox1" runat="server" Width="220px"></asp:TextBox>
    <br />
    <br />
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search Data" />
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>

</form>
</body>
</html> 

Code Behind

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class my : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString =ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    con.Open();

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "select * from [Department] where dept_no=" + TextBox1.Text;
    cmd.Connection = con;
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();


}
}
Now code Generate the following output

Wednesday, November 19, 2014

Data Modification Language (DML) Triggers in SQL

A DML trigger is fired when data in the underlying table is affected by DML statements, such as INSERT, UPDATE, or DELETE. These triggers help in maintaining consistent, reliable, and correct data in tables. They enable the performance of complex action and cascade these actions to other dependent tables. Cascading is the process of reflecting the changes made in a table in the other related tables.
The DML triggers have the following characteristics:
Fired automatically by the SQL Server whenever any data modification statement is issued.
Cannot be explicitly invoked or executed, as in the case of the stored procedures.
Prevents incorrect, unauthorized, and inconsistent changes in data.
Cannot return data to the user.
Can be nested up to 32 levels. The nesting of triggers occurs when a trigger performs an action that initiates another trigger.

Whenever a trigger is fired in response to the INSERT, DELETE, or UPDATE statement, the SQL Server creates two temporary tables, called magic tables. The magic tables are called inserted and deleted. The magic tables are conceptual tables and are similar in structure to the table on which the trigger is defined.
The inserted tale contains a copy of all records that are inserted in the trigger table. The Deleted table contains all records that have been deleted from the trigger table. Whenever you update data in a table, the trigger uses both the inserted and the deleted tables.
Depending on the operation that is performed, the DML trigger can be further categorized as:
Insert trigger: is fired whenever and attempt is made to insert a row in the trigger table. When an INSERT statement is executed, a new row is added to both the trigger and the inserted tables.
Delete trigger: is fired whenever an attempt is made to delete a row from the trigger table. When a DELETE statement is executed, the specified rows from the trigger table are deleted and are added to the deleted table. The deleted and trigger tables do not have any rows in common, as in the case of the inserted and trigger tables.
There are three ways of implementing referential integrity by using a DELETE trigger. These are:
The cascade method: Deletes records from the dependent tables whenever a record is deleted from the master table.
The restrict method: Restricts the deletion of records from the master table if the related records are present in the dependent tables.
The nullify method: Nullifies the values in the specified columns of the dependent tables whenever a record is deleted form the master table.
Update trigger: Is fired when a UPDATE statement is executed in the trigger table. It uses two logical tables for its operations, the deleted table that contains the original rows (the rows with the values before updating) and the inserted table that stores the new tows (the modified rows). After all the rows are updated, the deleted and inserted tables are populated and the trigger is fired.
For example, you have a table with three columns. The table stores the details of hardware devices. You updated a value in column 2 from ‘Printer’ to ‘Lex New Printer’. During the update process, the deleted table holds the original row (the row with the values before updating), and inserted table stores the new row (the modified row) with the value ‘Lex New Printer’ in Column2.

Sunday, November 16, 2014

How to add controls dynamically in windows form c#

Visual studio provide the best features to design the form. By the designer window, you can add the controls from the toolBox. After added the items, you can set the properties by the property window. Same this things, you can do this by the code window. Follow some steps to add controls dynamically.


  Step-1 : Open Code window that is form1.cs file, create a object for controls like

TextBox t1 = new TextBox();

Step-2 : Associate properties of the TextBox class with the current object like

 t1.Name = "Text1";
    t1.Width = 300;
            t1.Text = " Dynamically added Control";
            t1.Location = new Point(10, 10);

Here Point is a class, in which you have to define the coordinates of x-axis and y-axis, where you want to add the TextBox.

Step-3 : Add this instance in the form by following line of code.

 this.Controls.Add(t1);

 Now code Generate the following output:
How to add controls dynamically in windows form c#

Friday, November 14, 2014

Design a program to find largest of four numbers

The logic behind the program is, Take four variable like a, b, c, d for numbers also take another variable like large for comparing among three numbers. First of all, assign the value of variable a into the large variable. Compare among three numbers with the large variable. If any one is find larger then you have to assign this variable value into the larger variable.

Example

#include <stdio.h>
#include<conio.h>
main()
{
int a,b,c,d;
int large;

clrscr();
printf("Enter four numbers:\n");
scanf("%d%d%d%d",&a,&b,&c,&d);
large=a;
if(b>large)
large=b;
if(c>large)
large=c;
if(d>large)
large=d;
printf("The largest number is %d",large);
}

Output Of the Given program is

Tuesday, November 11, 2014

How to draw rectangle in applet

Four coordinate are required For drawing the rectangle in the java applet. First two coordinate define the origin point of the rectangle. Origin point start from upper left corner and further x-coordinate increases width of the rectangle in right side and y-coordinate increases height of the rectangle in downward.

Syntax of drawRect in Java Applet

Graphics_Instance . drawRect(int X1, Int Y1, int Width, int Height);

If you want to set border color of the rectangle then use setColor( ) method of Graphics class, which is exist in java.awt package.

Example - designline.java

import java.awt.*;
import java.applet.*;
public class designline extends Applet
{
int width, height;

   public void init() {
   
      setBackground( Color.gray);
   }

   public void paint( Graphics g ) {

   

      g.setColor( Color.red );
      g.drawRect( 11, 22, 101, 50 );
}
}
First to compile the code and create the class file for this
First to compile the code and create the class file for this
Prepare the HTML file in the same location with <applet> tag. Like

<applet code="designline" width="400" height="400" />

Save the .html file in same location also run in any browser.

How to draw rectangle in applet

How to draw Line in Applet

Four coordinate are required For drawing the line in the java applet. First two coordinate define the origin point of the line. Origin point start from upper left corner and further x-coordinate increase in right side and y-coordinate increase downward.

Syntax of drawLine in Java Applet

Graphics_Instance . drawLine(int X1, Int Y1, int X2, int Y2);

If you want to set color on line then use setColor( ) method of Graphics class, which is exist in java.awt package.

Example - designline.java

import java.awt.*;
import java.applet.*;
public class designline extends Applet
{
int width,height;
public void init()
{
setBackground(Color.black);

}
public void paint(Graphics g)
{

g.setColor(Color.green);
g.drawLine(0,0,200,200);
}
}

Compilation of Applet code and generate the class file

Compilation of Applet code and generate the class file

Prepare the HTML file in the same location with <applet> tag. Like

<applet code="designline" width="400" height="400" />

Save the .html file in same location also run in any browser.

Code Generate the following output

How to draw Line in Applet

Using the init ( ) method, you can set the back ground color of the applet. Also set the line color using the graphics class. 

Monday, November 10, 2014

Compiling and Running Java Programs

There are various steps to compiling and running java programs, these are
Step-1 : First to install JDK, JRE and JVM into the System.
Step-2 : Prepare source code in any editor like notepad, c++ editor etc.
Step-3:

class HelloWorld
{
public static void main(String r[])
{
int a=10, b=10,c;
c=a+b;
System.out.println("Output of the program is"+c);
}
}

Step-4 : Save the source code in the java bin directory. Class name which contain main method should same of the file name.
Example :  HelloWorld (class name)
                  HelloWorld.java (file name)

Step-5 : Open command prompt and change the directory where your java program has been saved.
Suppose your java software installed in C:/>. Now, compiling steps is:

C:/java/jdk1.7.0/bin> Javac filename.java   (press Enter)
C:/java/jdk1.7.0/bin> Java  filename.java    (press Enter)

Step-6: During compilation, if program generate errors, it means you can't run your program.                 

Sunday, November 9, 2014

Execute Batches multiple times using Stored Procedures in SQL

Batches are temporary in nature. To execute a batch more than once, you need to recreate SQL statements and submit them to the server. This leads to an increase in the overhead, as the server needs to compile and create the execution plan for these statements again. Therefore, if you need to execute a batch multiple times, you can save it within a stored procedure. A stored procedure is a precompiled object stored in the database.

Stored procedures can invoke the Data Definition Language (DDL) and Data Manipulation Language (DML) statements and can return values. If you need to assign values to the variables declared in the procedures at the run time, you can pass parameters while executing them. You can also execute a procedure from another procedure. This helps in using the functionality of the called procedure within the calling procedure.

Creating Stored Procedures

You can create a stored procedure by using the CREATE PROCEDURE statement. The syntax of the CREATE PROCEDURE statement is:
CREATE PROCEDURE proc_name
AS
BEGIN
Sql_statement1
Sql_statement2
END
Where Proc_name specifies the name of the stored procedure.

The following example create a stored procedure to view the department names from the Department table:
CREATE PROCEDURE prcDept
AS
BEGIN
SELECT Name FROM HumanResources.Department
END
When the CREATE PROCEDURE statement is executed, the server compiles the procedure and saves it as a database object. The procedure is then available for various applications to execute. The process of compiling a stored procedure involves the following steps:

  • The procedure is compiled and its components are broken into various pieces. This process is known as parsing.
  • The existence of the referred objects, such as tables and views, are checked. This process is known as resolving.
  • The name of the procedure is stored in the sysobjects table and the code that creates the stored procedure is stored in the syscomments table.
  • The procedure is compiled and a blueprint for how the query will run is created. This blueprint is specified as execution plan. The execution plan is saved in the procedure cache.
  • When the procedure is executed for the first time. The execution plan will be read and fully optimized and then run. The net time the procedure is executed in the same session, it will be read directly from the cache. This increases performance, as there is no repeated compilation.

After creating the stored procedure, you can view the code of the procedure by using the sp_helptext command.

Implementing Triggers and its Types in SQL

In a relational database, data in a table is related to other tables. Therefore, while manipulating data in one table, you need to verify and validate its effect on data in the related tables. In addition, you might need to manipulate data in a table after inserting or updating data in another table.

You also need to ensure that if an error occurs while updating the data in a table, the changes are reverted. This helps in maintaining data integrity. The SQL Server allows you to implement triggers and transactions to maintain data integrity.

This article explains different types of triggers that can be created in SQL Server. Next, we will discusses how to implement triggers to enforce data integrity. Further, we will discuss about how to implement transactions.

Implement Triggers

At times, while performing data manipulation on a database object, you might also need to perform another manipulation on another object. For example, in an organization, the employees use the Online Leave Approval system to apply for leaves. When an employee applies for a leave, the leave details are stored in the Leave-Details table. In addition, a new record is added to the Leaves-For-Approval table. When the supervisors log on to the system, all the leaves pending for their approval are retrieved from the Leaves-For-Approval table and displayed to them.

To perform such operations, the SQL Server allows you to implement triggers. A trigger is a block of code that constitutes a set of T-SQL statements activated in response to certain actions, such as insert or delete. Triggers are used to ensure data integrity before or after performing data manipulations.

Before you implement a trigger, it is important to know the different types of triggers that can be created by using SQL Server.

Identifying Types of Triggers

In the SQL Server, various kinds of triggers can be used for different types of data manipulation operations. The SQL Server supports the following types of triggers:

Data Modification Language (DML) triggers

A DML trigger is fired when data in the underlying table is affected by DML statements, such as INSERT, UPDATE, or DELETE. These triggers help in maintaining consistent, reliable, and correct data in tables. They enable the performance of complex action and cascade these actions to other dependent tables. Cascading is the process of reflecting the changes made in a table in the other related tables.

Data Definition Language (DDL) triggers

A DDL trigger is fired in response to DDL statements, such as CREATE TABLE or ALTER TABLE. DDL triggers can be used to perform administrative tasks, such as database auditing.

Commonly used jQuery Event Methods: jQuery

All the DOM events have its equivalent jQuery methods that may be implement by programmer as per the requirement. Anything happens through input devices on the web-page is called an event.

All these events have its unique names e.g. clicking on the page, pressing key, hovering mouse etc. According to jQuery masters, these events have some categories, some of them listed below:

  • Keyboard events: KeyDown, KeyUp and KeyPress etc.
  • Mouse events: Click, double click, mouse hover, mouse enter and mouse leave etc.
  • Form events: submit, focus, blur etc. 
  • Document/window events: Load, UnLoad, scrolling, resizing etc.

All these events have its own method, discussed earlier in changing default behavior. Some of those events have listed below with example:

$(document).ready()

Whenever the document/page is ready, this event have triggered. Anything written in this event have been executed just after the page loaded. All the events except functions must be written in this event to be executed. Some of the selectors have been discussed here.
$(document).ready(function(){
alert(‘document is ready’); // This message will shown just after the page load its contents.
});

click()

This event triggers when user clicks on any html events. Programmer can write particular click method on any html event. The below code will execute when user clicks on any <p> element.
$(“p”).click(function(){
alert(‘p tag clicked’);
});

dblclick()

This event triggers when user double clicks on any html events. Programmer can write particular double click method on any html event. The below code will execute when user clicks two times on any <p> element.
$(“p”).dblclick(function(){
alert(‘p tag double clicked’);
});

mouseenter()

This event triggers when user enters mouse in the area of html events. The below code will execute when user enters into area of any <p> element.
$(“p”).mouseenter(function(){
alert(‘mouse entered in <p> tag’);
});

blur()

whenever an html event losses its focus, this event will triggered. This is just opposite event of focus() event which triggers when an element have focus on it.
$(“p”).blur(function(){
alert(‘losses focus from <p> tag’);
});

There are many events related to each html element, can be read from jQuery official website of through the help option of visual studio. All those events have similar syntax to write method for them. In the next article we will discuss about jQuery effects.

Saturday, November 8, 2014

Merits of bottom-up technique


  • The details of the sub-problem solutions are available in advance in the form of bottom level modules.
  • The individual sub-problem solutions are designed with great details.
  • The main solution can be planned later depending on the available sub-task solutions.
  • The main solution is used to link all the sub-problem solutions.
  • The sub-solutions obtained are simple
  • A complex main module is designed later using these simpler solutions.
  • This technique is more general and code are reusable.
  • This technique simplifies maintenance and the new features can be added easily.
  • This decision of the final solution can be delayed to make it more effective for implementation.
  • Testing in this case is simple and test cases can be designed very easily.

Demerits of top-down technique


  • This technique is mainly useful for small-scale problems.
  • It is only useful in solving a part of a larger problem.
  • This technique is a poor approach for solving larger problems 
  • This technique is also poor for designing larger programs.
  • The application developed using this technique cannot be upgraded easily.
Related Links





Merits of top-down technique


  • The summary of the program plan is known in advance in the form of top module.
  • Parallel development of the program is possible because of independent design of the modules at different levels.
  • Parallel development helps in designing the program at reduced time period.
  • Testing and debugging are faster because of independent testing of modules.
  • Attention can be given to individual level task to improve the efficiency.
  • The hierarchy of the levels helps in understandable low level modules.
  • Handling and management of the modules are easy.
  • This technique improves the code reliability.

Features of top-down technique


  • Program preparation is stretched to a number of levels 
  • In place of writing long list of statements, the statements are separated into different modules at various levels.
  • The stretching is most general to most specific.
  • Program is structured as hierarchy of various tasks.
  • As the techniques moves from top to bottom, it is a type of specialization.
  • Main module can be designed well before without requiring details of complete design.
  • Testing can be done after inserting down level modules one-by-one.
  • Parallel development is possible because of top and down level modules design.

Rules for making Flowchart

"What are the rules for making the flowchart?"

Rule 1: The flowchart should contain one start and one stop box (terminator).
Rule 2: The symbols of the flowchart are always labeled with simple codes.
Rule 3: The codes used in the flowchart should not give more than one meaning.
Rule 4: The control flows are always represented by directed arrows.
Rule 5: The control flow lines touch the boundary of any box either while leaving from or while entering into the box.
Rule 6: The control flow lines should not cross each other.
Rule 7: The flow line moves in vertical direction either from top to bottom or from bottom to top.
Rule 8: The flow line moves in horizontal direction either from left to right or from right to left.
Rule 9: Only one flow line comes out from all the boxes or symbols excepts decision box.
Rule 10: Two lines can flow from the decision box if single condition is checked. It means a single condition results in one of the two values TRUE or FALSE

Design an algorithm to search a number using binary search technique

Binary Search algorithm is applied where we want to search number in sorted numbers. In this algorithm, first to find mid position of the list and divide the list into two parts. If number is equal to mid then position find easily , this is the  best case of binary search.
Problem: Design an algorithm to search a number using binary search technique.
Input : A list (array) of numbers in ascending order, number of elements in the list and key to search.
Output: Returns 1 if the key is found otherwise returns 0

BIN_SEARCH(LIST, N, KEY)
[LIST is an array of numbers in ascending order]
[N is the size of the array and KEY is the number to search]
L <-- 0;  H<-- N-1;  [Assuming that array index start from 0]
M <-- INT ( (L+H) /2 ) [Get the quotient or integer part after division]

Repeat While (L <= H)
If(Key == LIST[M]) then:
Return 1                [Key found]
Else:
If(Key < LIST[M] ) then:
H <-- M-1                     [Move to the left half of the list]
Else:
H <-- M+1                    [Move to the right half of the list]

        [End of If]
     [End of If]
  [End of While]
  Return 0                                         [Key not found]
  Exit.

Friday, November 7, 2014

Design an algorithm to search a number using linear search technique

Problem: Design an algorithm to search a number using linear search technique.
Input :  A list (array) of numbers, number of elements in the list and key to search.
Output : Returns 1 if the key is found otherwise returns 0.

LSEARCH(LIST, N, KEY)

[LIST is an array of numbers, N is the size of the array and key is the number to search]
Repeat For I=0, 1, 2, 3......N-1 [Assuming that array index starts from 0]
If(Key == LIST[I]) then:
Returns 1
[End of If]
Returns 0
Exit.





Design an algorithm to find sum of 'N' natural numbers

Problem: Design an algorithm to find sum of 'N' natural numbers between N1 and N2.
Input : Two numbers N1 and N2.
Output: Sum of N natural numbers.

SUM(N1, N2)

[N1 and N2 are two different natural numbers]
If N1> N2 then:
MAX <-- N1
MIN <-- N2
ELSE:
MAX<-- N2
MIN <-- N1
[End of If]
MIN <-- MIN-1 [ to include MIN in sum]
SUM 1 <-- (MIN * (MIN+1))/2
SUM 2 <-- (MAX * (MAX+1))/2
Return SUM2- SUM1
Exit.

In the above algorithm to find the sum of N natural numbers, the formula N(N+1)/2 is used. Instead of a formula, repetitive statements can also be used that run from MIN to MAX with step 1. The algorithm can be re-written as:

II algorithm 

Problem: Design an algorithm to find sum of 'N' natural numbers between N1 and N2.
Input : Two numbers N1 and N2.
Output: Sum of N natural numbers.

SUM(N1, N2)

[N1 and N2 are two different natural numbers]
If N1> N2 then:
MAX <-- N1
MIN <-- N2
ELSE:
MAX<-- N2
MIN <-- N1
[End of If]
SUM <-- 0
Repeat For I= MIN, MIN+1, MIN+2..........MAX
SUM <-- SUM+1
[End of For]
Return SUM
Exit.

Tracing:
Suppose that the above algorithm SUM1 is called with two numbers 23 and 11.
In the If statements 23>11 condition is TRUE, therefore MAX becomes 23 and MIN becomes 11.
Now the loop repeats for 11, 12, 13, 14 up to 23
(I values).
Every time when the loop is repeated I is added to SUM.
So, finally the value of SUM is returned from the algorithm.

Design an algorithm to find the GCD and LCM of two positive numbers

Problem : Design an algorithm to find the GCD (Greatest Common Divisor) of two positive numbers and use the same to find LCM of two positive numbers.

Input: Two Numbers
Output : Least Common Multiple of two numbers.

GCD(NUM1, NUM2)
Rem <-- NUM1 % NUM2  [% Modulus Operator]
Repeat While Rem <> 0
NUM1 <-- NUM2
NUM2 <-- Rem
Rem <-- NUM1 % NUM2
[End of While]
Return NUM2
Exit.

LCM(NUM1, NUM2)
Return (NUM1 * NUM2) / GCD( NUM1, NUM2)
Exit.

NOTE : Here in this example algorithm, finding LCM in the main problem that can be divided into sub-problem like finding the GCD first and using the same to solve the main problem. So, GCD algorithm is written first and than the other algorithm that can be divided into small problems and algorithm can be written to solve such small problems.

Tracing

Suppose that the LCM algorithm is called using 12 and 16. The algorithm calls GCD with 12 and 16.

Rem <-- 12 % 16 i.e. Rem= 12
Rem is not equal to zero. So, NUM1=16 and NUM2 =12
Rem<-- 16%12 i.e. Rem=4
Rem is not equal to Zero. So, NUM1 =12 and NUM2 =4
Rem <-- 12 % 4 i.e. Rem=0
Rem is equal to Zero.
So, GCD algorithm returns NUM2 that is 4.

When the algorithm LCM gets the result from GCD algorithm its find the expression value
(NUM1 * NUM2) / GCD (NUM1, NUM2).  i.e. (12 * 16)/4

It is equal to 48. 48 is the LCM of 12 and 16

Design an algorithm to find minimum of two distinct numbers

Problem:  Design an algorithm to find minimum of two distinct numbers and using the same, find minimum of three distinct numbers.

Input :  For sub-algorithm 2 numbers and for main algorithm 3 numbers.
Output: Minimum number

MIN_OF_2(NUM1, NUM2)                                                   [Sub-Algorithm]
[NUM1 and NUM2 are two numbers]
If NUM1<NUM2 Then:
Return NUM1
Else:
Return NUM2
[End of If]
Exit

MIN_OF_3(NUM1,NUM2,NUM3)                                     [Main Algorithm]
[NUM1, NUM2, and NUM3 are distinct numbers]
Returns MIN_OF_2(MIN_OF_2(NUM1, NUM2), NUM3)
Exit

Algorithm to find maximum of two unequal numbers

Problem: Algorithm to find maximum of two unequal numbers and use the same to find maximum of four unequal numbers.

Input: For sub-algorithm 2 numbers and for main algorithm 4 numbers.

Output : Returns the maximum of 4 numbers

MAX_OF_2(NUM1, NUM2)      [Sub-algorithm]
[NUM1 and NUM2 are two numbers]
If(NUM1>NUM2) Then:
Returns NUM1
Else:
Return NUM2
[End of If]
Exit.
MAX_OF_4(NUM1, NUM2, NUM3, NUM4)
[NUM1, NUM2, NUM3, and NUM4 are numbers]
TEMP1 <-- MAX_OF_2(NUM1, NUM2)
TEMP2 <-- MAX_OF_2(NUM3, NUM4)
MAX   <-- MAX_OF_2(TEMP1, TEMP2)
Return MAX
Exit.

Design an algorithm to find average of salary

This example is little complex. You will understand it more clearly after reading the user defined data types.
Problem: Design an algorithm to find average of SALARY in an array of EMP struct containing information EMPNO, EMPNAME, and SALARY.
Input: A list employees of the type struct.
Output : Display the average of SALARY.

AVG_SALARY(LIST, SIZE)
[LIST is an array of EMP, SIZE is size of array]
SUM<-- 0
Repeat For I=1,2,3,........SIZE
SUM<--SUM +LIST[I].SALARY
[END of For I]
AVG <-- SUM / SIZE
Write :  'The average Salary is', AVG
Exit

Note : An algorithm, that perform sub-task, may be called in another algorithm. It is a better practice to divide the given problem into sub-problems ans write the individual algorithm to solve such sub-problems. Write the main algorithm to call the sub-algorithms in order to solve the main problem.




Thursday, November 6, 2014

Design an algorithm to find the average

Problem :  Design an algorithm to find the average of a subject marks of 'N' number of students.
Input: A list of marks and number of students.
Output: Returns the average marks calculated.

AVG_OF_MARKS(LIST,N)
[LIST is an array containing marks, N is the size of array]
SUM <-- 0
Repeat For I=1,2,3,.........N
SUM<-- SUM+LIST[I]
[END of For I]
AVG <-- SUM/N
Returns AVG
Exit



Design an algorithm to find the grade on the basis of the following criteria

Marks Obtained                                                                                       Grade
85 or above 85                                                                                             S
75 or above 75                but less than 85                                                    A
65 or above 65                but less than 75                                                    B
55 or above 55                but less than 65                                                    C
50 or above 50                but less than 55                                                    D
Less than 50                                                                                                 F

Input:      Marks obtained
Output  : Returns the grade on the basis of given criteria

GRADE(M)
[M is the marks obtained]
if(M>= 85) Then:
Returns 'S'
Else:
If (M>= 75) Then:
Returns 'A'
Else:
If(M>=65) Then:
Returns 'B'
Else:
If(M>= 55) Then:
Returns 'C'
Else
If(M>=50) Then:
Returns 'D'
Else
Returns 'F'
[End of If]
[End of If]
Exit.

Wednesday, November 5, 2014

Creating Table-Valued Functions in SQL

A table-valued function returns a table as an output, which can be derived as a part of a SELECT statement. Table-valued function return the output as a table data type. The table data is a special data type used to store a set of rows, which return the result set of a table-valued function. Table-valued functions are of two types:

Inline Table-Valued Function

An inline table-valued function returns a variable of a table data type from the result set of a single SELECT statement. An inline function does not contain a function body within the BEGIN and END statements.

Consider an example where the inline table-valued function, fx_Department_GName, accepts a group name as parameter and returns the details of the departments that belong to the group from the Department table. You can create the function by using the following statement:

CREATE FUNCTION fx_Department_GName ( @GrName nvarchar (20) )
RETURNS table
AS
RETURN (
SELECT *
FROM HumanResources.Department
WHERE GroupName=@GrName
)
GO

You can use the following statement to execute the fx_Department_Gname function with a specified argument:

SELECT * FROM fx_Department_GName (‘Manufacturing’)

The preceding statement will return a result set having the group name ‘Manufacturing’.

Consider another example of an inline function that accepts rate a a parameter and returns all the records that have a rate value greater than the parameter value:

CREATE FUNCTION HumanResources.Emp_Pay (@Rate int)
RETURNS table
AS
RETURN (
SELECT e.EmployeeID, e.Title, er.Rate
FROM HumanResources.Employee AS e
JOIN HumanResources.EmployeePayHistory AS er
ON e.EmployeeID=er.EmployeeID WHERE er.Rate<@Rate
)
GO
The preceding function will return a result set that displays all the records of the employees who have the pay rate greater that the parameter.

Multistatement Table-Valued Function

A Multistatement table-valued function uses multiple statements to build the table that is returned to the calling statement. The function body contains a BEGIN…END block, which holds a series of T-SQL statements to build and insert rows into a temporary table. The temporary table is returned in the result set and is created based on the specification mentioned in the function.

Consider an example where the Multistatement table-valued function, PayRate, is created to return a set of records from the EmployeePayHistory table by using the following statements:

CREATE FUNCTION PayRate (@rate money)
RETURNS @table TABLE
(EmployeeID int NOT NULL,
RateChangeDate datetime NOT NULL,
Rate money NOT NULL,
PayFrequency tinyint NOT NULL,
modifiedDate datatime NOT NULL)
AS
BEGIN
INSERT @table
SELECT *
FROM HumanResources.EmployeePayHistory
WHERE Rate > @rate
RETURN
END

The function returns a result set in from of a temporary table, @table, created within the function. You can execute the function by using the following statement:

SELECT * FROM PayRate (45)

Depending on the result set returned by a function can be categorized as deterministic or nondeterministic. Deterministic functions always return the same result whenever they are called with a specific set of input values. However, nondeterministic function may return different results each time they are called with a specific set of input values.
An example of a deterministic function is date add, which returns the same result for any given set of argument values for its three parameters. Get date is a nondeterministic function because it is always invoked without any argument, but the return value changes on every execution.


Tuesday, November 4, 2014

Creating Scalar functions in SQL

In earlier article we have discussed about user defined functions that have the limited scope in sql programming in compare to stored procedures. User defined function have two types i.e. scalar function and table-valued function. In this article we will discuss about scalar functions.

Scalar function accept a single parameter and return a single data value of the type specified in the RETURNS clause. A scalar function can return any data type except text, ntext, image, cursor, and timestamp. Some scalar functions, such and current_timestamp, do not require any arguments.

A function contains a series of T-SQL statements defined in a BEGIN…END block of the function body that returns a single value.

Consider an example of a scalar function that calculates the monthly salary of the employees accepting the pay rate as an input and returning a single value after multiplying the value with the number of hours and number of days:

CREATE FUNCTION HumanResources.MonthlySal (@PayRate float)
RETURN float
AS
BEGIN
RETURN (@PayRate * 8 * 30)
END

You can execute this function by using the following statements:

DECLARE @PayRate float
SET @PayRate = HumanResources.MonthlySal (12.25)
PRINT @PayRate

In the preceding code, @PayRate is a variable that will store a value returned by the MonthlySal function.

© Copyright 2013 Computer Programming | All Right Reserved