-->

Sunday, April 27, 2014

How to Create Partition Function for Particular Column: SQL

A partition function specifies how a table should be partitioned. It specifies the range of values on a particular column. Based on which the table is partitioned. For example, in the scenario of Adventure Works, you can partition the data based on years. The following statement creates a partition function for the same:

CREATE PARTITION FUNCTION RateChangDate, (datetime)
AS RANGE RIGHT FOR VALUES (‘1996-01-01’, ‘2000-01-01’, ‘2004-01-01’, ‘2008-01-01’)

The preceding query creates a partition function named RateChangDate. It specifies that the data pertaining to the change in the payment rate will be partitioned based on the year.

Creating a Partition Scheme

After setting the partition function, you need to create the partition scheme. A partition scheme associates a partition function with various filegroups resulting in the physical layout of the data. Therefore, before creating a partition scheme, you need to create filegroups.

To create partition filegroups, you need to perform the following steps:

  • Expand the Database folder in the Object Explorer windows and right-click the AdventureWorks database.
  • Select the Properties option from the short-cut menu to display the Database Properties – AdventureWorks window.
  • Select the Filegroups folder from Select a page pane to display the list of all the filegroups in AdventureWorks.
  • Click the Add button to add a filegroup. Specify the name of the filegroup in the Name text box as Old.
  • Report Step 4 to add four more filegroups named First, Second, Third, and Fourth, as shown in the following figure.

    How to Create Partition Function for Particular Column: SQL
  • Select the Files folder from Select a page pane to display the list of all the files.
  • Click the Add button and type the name of the file as OldFile in the Logical Name text box, and select Old from the Filegroup drop-down list.
  • Report Step 7 to create four files names File1, File2, File3, File4, select filegroup as First, Second, Third, Fourth for the files.
  • Click OK button to close the Database Properties – AdventoreWorks window.

Execute the following statements in the Microsoft SQL Server Management
CREATE PARTITION SCHEME RateChangDate
AS PARTITION RateChangDate
TO (Old, First, Second, Third, Fourth)


Create partitioned table in sql

How to Create Partitioned Table in SQL Server

When the volume of data in a table increases and it takes time to query the data, you can partition the tables and store different parts of the tables in multiple physical locations based on a range of values for a specific column. This helps in managing the data and improving the query performance.

Consider the example of a manufacturing organization. The details of inventory movements are stored in the InventoryIssue table. The table contains a large volume of data and the queries take a lot of time to execute thereby slowing the report generation process.

To improve the query performance, you can partition the table to divide the data based on a condition and store different parts of the data in different locations. The condition can be based on the date of transaction and you can save the data pertaining to five years at a location. After partitioning the table, data can be retrieved directly from a particular partition by mentioning the partition number in the query.

In the preceding example, the partitioned table were created after the database had already been designed. You can also create partitioned tables while designing the database and creating tables. You can plan to create a partitioned table when you know that the data to be stored in the table will be large. For example, if you are creating a database for a banking application and you know that the transaction details will be voluminous, you can create the transaction table s with partitions.

Partitioning a table is only allowed in Enterprise Edition of SQL Server. To create a partitioned table, perform the following tasks:

  • Create a partition function.
  • Create a partition scheme.
  • Create a table by using the partition scheme.

For example, the AdventureWorks database stores the data of all the employees for the last 11 years. This data includes the personal details of the employees and their payment rates. Whenever there is a change in the payment rate of an employee, it is recorded in a separate record. However, this result in generation of large volume of data. This adversely affects the query performance.

To improve the query performance, the database developer needs to partition the table storing the changes in wage rate.

Create Rule and User-defined DataType

How to use LINQ Generation operators in ASP.NET

Introduction

The Generation operators help in creating a new sequence of values. The Generation operators are DefaultlfEmpty, Empty, Range, and Repeat. The DefaultlfEmpty clause replaces an empty collection with a default single collection. The Empty clause refers to an empty collection. The Range clause generates a collection that contains a sequence of numbers. The Repeat clause generates a collection that contains at least one repeated value.
The syntax of Range clause is:
For C#
public static IEnumerable<int> Range( int start, int count);
The Range clause throws an ArgumentOutOfRangeException exception if the count is less than 0, or if the start + or count -1 parameters are larger than the maximum value.
The syntax of the Empty clause is:
For C#
public static IEnumerable<T> Empty<T>();
The Empty clause caches a single empty sequence of the given type.

Lets take an simple example

<form id="form1" runat="server">
    <div>
    
        <asp:ListBox ID="ListBox1" runat="server" Height="254px" Width="153px">
        </asp:ListBox>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text="odd and even " />
    
    </div>
    </form>
Code Behind 
protected void Button1_Click(object sender, EventArgs e)
    {
        var num = from n in Enumerable.Range(1, 20)
                  select new { Number = n, oddevennumber = n % 2 == 1 ? "odd" : "even" };
        foreach (var item in num)
        {
            ListBox1.Items.Add("The number is " + item.Number + item.oddevennumber);
            
        }
    }
Code Generate the following output
How to use LINQ Generation operators in ASP.NET

How to Create Rule and User Defined Data Type in SQL

A rule enforces domain integrity for columns or user-defined data types. The rules is applied to the column of the user-defined data type before an INSERT or UPDATE statement is issued. In other words, a rule specifies a restriction on the values of a column or a user-defined data type. Rules are used to implement business-related restrictions or limitations. A rule can be created by using the CREATE RULE statement.

The syntax of the CREATE RULE statement is:
CREATE RULE rule_name AS conditional_expression
Where,

  • Rule_name specifies the name of the new rule that must conform to rules for identifiers.
  • Conditional_expression specifies the condition(s) that defines the rule. It can be any expression that is valid in a WHERE clause and can include elements, such as arithmetic operators, relational operators, IN, LIKE, and BETWEEN.

The variable specified in the conditional expression must be prefixed with the @ symbol. The expression refers to the value that is being specified with the INSERT or UPDATE statement.

In the preceding example of the EmployeeLeave table, you applied a rule to accept only three values: ‘CL’, ‘SL’, and ‘PL’. You can perform the same task by creating a rule. You can use the following statement to create the rule:
CREATE RULE rulType
AS @LeaveType IN (‘CL’, ‘SL’, ‘PL’)

After you create the rule, you need to activate the rule by using a stored procedure, sp_bindrule.

The syntax of sp_bindrule is:
Sp_bindrule <’rule’>, <’object_name’>, [<’futureonly_flag’>]
Where,

  • Rule specifies the name of the rule that you want to bind.
  • Object_name specifies the object on which you want to bind the rule.
  • Futureonly_flag applies only when you want to bind the rule to a user-defined data type.

Using a user defined data type

User-defined data types are custom data types defined by the users with a custom name. User-defined data types allow modifying the composite data type used in the database. The user-defined data types are based on the system data types and can be used to predefine several attributes of a column, such as its data type, length, and whether it supports NULL values.

You can create user-defined data types by using the CREATE TYPE statement. The syntax of the CREATE TYPE statement is:
CREATE TYPE [schema_name. ] type_name {FROM base_type [ ( precision [, scale ] ) ] [ NULL | NOT NULL ] } [;]
Where,

  • Schema_name specifies the name of the schema to which the alias data type or the user-defined data type belongs.
  • Type_name specifies the name of the alias data type or the user-defined data type.
  • Base_type specifies the SQL Server supplied data type on which the alias data type is based.
  • Precision specifies the decimal or numeric point. Decimal and numeric are non-negative integers that indicate the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point.
  • Scale specifies the decimal or numeric scale.
  • NULL | NOT NULL specifies whether the data type can hold a null value. If not specified, NULL is the default value.

The following SQL query creates a user-defined data type for descriptive columns:
CREATE TYPE DSCRP
FROM varchar (100) NOT NULL;

In the preceding example, a user-defined data type DSCRP is created to store the varchar data type and the size limit is specified as 100. Further, it also specifies NOT NULL. Therefore, you can use this data for the columns that hold description, address, and reason.

For example, you can use the DSCRP data type to store the data of the LeaveReason column of the EmployeeLeave table, as shown in the following statement:

CREATE TABLE HumanResources.EmployeeLeave
(
EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES
HumanResources.Employee (EmployeeID),
LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY (EmployeeID, LeaveStartDate),
LeaveEndDate datetime NOT NULL,
LeaveReason DSCRP,
LeaveType char(2) CONSTRAINT chkLeave CHECK (LeaveType IN (‘CL’, ‘SL’, ‘PL’)) CONSTRAINT chkDefLeave DEFAULT ‘PL’)

Solve Decision-Making Expression using Logical Operators in JAVA

Relational operators often are used with logical operators (also known as conditional operators sometimes) to construct more complex decision-making expression. The Java programming language supports six conditional operators-five binary and one unary-as shown in the following image.


The logical OR operator (||)

The logical OR operator (||) combines two expressions which make its operands. The logical OR (||) operator evaluates to Boolean true if either of its operands evaluate to true.

This principle is used while testing evaluating expressions. Following are some examples of logical OR operation:

  • (4= =4) || (5 = =8)    results into true because first expression is true.
  • 1 = = 0 || 0 > 1         results into false because neither expression is true (both are false).
  • 5 > 8 || 5 < 2            results into false because both expression are false.
  • 1 < 0 || 8 > 0            results into true because second expression is true.

The operator || (logical OR) has lower precedence than the relational operators, thus, we don’t need to use parenthesis in these expressions.

The logical AND operator (&&)

The logical AND operator, written as &&, also combines two expressions into one. The resulting expression has the value true only if both of the original expression (its operands) are true. Following are some examples of AND operator (&&).

  • (6 == 3) && (4 == 4)           results into false because first expression is false.
  • (4 == 4) && (8 == 8)           results into true because both expressions are true.
  • 6 < 9 && 4 > 2                     results into true because both expressions are true.
  • 6 > 9 && 5 < 2                     results into true because both expressions are false.

Because logical AND operator (&&) has lower precedence than the relational operators, we don’t need to use parentheses in these expressions.

The logical NOT operator (!)

The logical NOT operator, written as "!", works on single expression or operand i.e. it is a unary operator. The logical NOT operator (!) negates or reverses the truth value of the expression following it i.e. if the expression is true, then expression is false, and vice versa.

Following are some examples of logical NOT operation:

  • ! (5 ! = 0) results into false because 5 is non zero (i.e., true)
  • ! (5 >2) results into false because the expression 5>2 is true.
  • !(5>9)  results into true because the expression 5>9 is false.

The logical negation operator "!" has a higher precedence then any of the relational or arithmetic operators. Therefore, to negate an expression, you should enclose the expression in parentheses:

!( x > 5 ) will reverse the result of the expression x > 5
    Whereas! x > 5 is equivalent to ( ! x ) > 5

i.e., it will first reverse the truth value of x and then test whether the reverse of x’s truth value is greater than 5 or not.

Relational Operators in JAVA

Compare Values using Relational Operators in JAVA

In the term relational operator, relational refers to the relationships that values (or operands) can have with one another. Thus, the relational operators determine the relation among different operands.

Java provides six relational operator for comparing numbers and characters. But they don’t work with strings. If the comparison is true, the relational expression results into the Boolean value true and to Boolean value false, if the comparison is false. The six relational operators are:

  • < (less than)
  • <= (less than or equal to)
  • == (equal to)
  • > (greater than)
  • >= (greater than or equal to) and
  • != (not equal to)

Summarizes the action of these relational operators.

Compare Values using Relational Operators in JAVA

t represents true and f represents false.
The relational operators have a lower precedence than the arithmetic operators. That means the expression
a + 5 > c – 2  ...expression 1
Corresponds to
( a + 5 ) > ( c – 2 ) ...expression 2
And not the following
a + ( 5 > c ) -2  …expression 3

Though relational operators are easy to work with, yet while working with them, sometimes you get unexpected results and behavior from your program. To avoid so, we would like you to know certain tips regarding relational operators.
Do not confuse the = and the = = operators.
A very common mistake is to use the assignment operators (=) in place of the relational operator (==). Do not confuse the testing the operator (==) with the assignment operator (=). For instance, the expression
Value = 3
Tests whether value is equal to 3? The expression has the Boolean value true if the comparison is true and Boolean false if it is false.

But the expression
Value = 3
Assigns 3 to value. The whole expression, in the case, has the value 3 because that’s the value of the left-hand side.
Avoid equality comparisons on floating-point numbers.
Floating-point arithmetic is not as exact and accurate as the integer arithmetic is. For instance, 3 X 5 is exactly 15, but 3.25 X 5.25 is nearly equal to 17.06 (if we are working with number with 2 decimal places). The exact number resulting from 3.25 X 5.25 is 17.0625.

Therefore, after any calculation involving floating-point numbers, there may be a small residue error. Because of this error, you should avoid the equality and inequality comparisons on floating-point number.
The relational operators group Left-to-right i. e., a <b<c means (a <b) < c and not a < ( b < c ).

Postfix version of operators 

How to use LINQ Conversion operators in ASP.NET

Introduction

Conversion operators convert a collection to an array. A Conversion operator changes the type of input objects. The different Conversion operators are ToSequence, ToArray, ToList, ToDictionary, ToLookup, OfType, and Cast.
The ToSequence clause simply returns the source argument by changing it to IEnumerable<T>. The ToArray clause enumerates the source sequence and returns an array containing the elements of the sequence. The ToList clause enumerates the source sequence and returns a List<T> containing the elements of the sequence. The ToDictionary clause lists the source sequence and evaluates the keySelector and elementSelector functions for each element to produce the element key and value of the source sequence. The ToLookup clause implements one-to-many dictionary that maps the key to the sequence of values. The OfType clause allocates and returns an enumerable object that captures the source argument. The Cast clause also allocates and returns an enumerable object that captures the source argument.
The syntax of the ToList clause is:


For C#
public static List<T> ToList<T>( this IEnumerable<T> source);

Lets take an simple example

<form id="form1" runat="server">
    <div>
 
        <asp:ListBox ID="ListBox1" runat="server" Height="143px" Width="143px">
        </asp:ListBox>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="String type" />
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click"
            Text="Integer Type" />
 
    </div>
    </form>
Code Behind
protected void Button1_Click(object sender, EventArgs e)
    {
        ListBox1.Items.Clear();
        var strtype = list.OfType<string>();
        ListBox1.Items.Add("String type value");
        foreach (var item in strtype)
        {
            ListBox1.Items.Add(item);
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

        ListBox1.Items.Clear();
        var strtype = list.OfType<int>();
        ListBox1.Items.Add("integer type value");
        foreach (var item in strtype)
        {
            ListBox1.Items.Add(item.ToString ());
        }

    }
Code Generate the following output
How to use LINQ Conversion operators in ASP.NET

How to use LINQ Conversion operators in ASP.NET

© Copyright 2013 Computer Programming | All Right Reserved