<feed xmlns="http://www.w3.org/2005/Atom">
	<title>Welcome to Shivshanker&#039;s Blog</title>
	<subtitle>
		I struggled to solve some problems so i want to share my solutions and who use these code they once test it and use it. 
	</subtitle>
	<id>@wiki</id>
	<link href="http://sscheral.atwiki.com/"/>
	<author>
		<name>23657</name>
	</author>
	<updated>
		2007-11-30T11:21:28Z
	</updated>
	
		<entry>
		<title>
			SQL UNION, SQL INTERSECT, SQL EXCEPT, SQL EXISTS and SQL CASE for Beginners
		</title>
		<link href="http://sscheral.atwiki.com/page/SQL%20UNION%2C%20SQL%20INTERSECT%2C%20SQL%20EXCEPT%2C%20SQL%20EXISTS%20and%20SQL%20CASE%20for%20Beginners" />
		

		<id>@wiki::40/</id>
		<published>
			2007-11-30
			
		</published>
		<updated>
			2007-11-30T11:21:28Z
		</updated>
		
		
				
		<summary>
			


SQL UNION, SQL INTERSECT, SQL EXCEPT, SQL EXISTS and SQL
CASE for Beginners

 
SQL
UNION, SQL
INTERSECT,
SQL EXCEPT, SQL
EXISTS and SQL CASE
Table1  




 


C1


C2




1


A


B




2


A


C




3


A


D




Table2




 


C1


C2




1


A


B




2


A


C




3


A


E




SQL
UNION
The purpose of the SQL
UNION command is to combine the results of
two queries together. In this respect,
UNION is somewhat similar to JOIN in that they are
both used to related information from multiple tables. One restriction
of UNION is that all corresponding columns need to be
of the same data type. Also, when using
UNION, only distinct values are selected (similar
to SELECT DISTINCT).
The purpose of the SQL
UNION ALL command is also to combine the
results of two queries together. The difference between UNION
ALL and UNION
is that, while
UNION only selects distinct values,
UNION ALL selects all
values.
The syntax is as
follows:
[SQL Statement
1]
UNION [ALL]
[SQL Statement
2]
 
The following are basic rules for combining
the result sets of two queries by using UNION:

·             The number and the order of the columns must be the same in all
queries.

·             The data types must be compatible.
 




SELECT C1,C2 FROM T1
UNION
SELECT C1,C2 FROM T2
 


SELECT C1,C2 FROM T1
UNION ALL
SELECT C1,C2 FROM T2




Result:
 




 


C1


C2




1


A


B




2


A


C




3


A


D




4


A


E






Result:




 


C1


C2




1


A


B




2


A


C




3


A


D




4


A


B




5


A


C




6


A


e








 
 
 
SQL
INTERSECT
Similar to the
UNION command,
INTERSECT also operates on two SQL
statements. The difference is that, while
UNION essentially acts as an
OR operator (value is selected if it appears
in either the first or the second statement), the
INTERSECT command acts as an
AND operator (value is selected only if it
appears in both statements). Returns distinct values by comparing the results
of two queries.

INTERSECT
returns any distinct values that are returned by both the query on the left and
right sides of the INTERSECT operand.

The basic rules
for combining the result sets of two queries that use INTERSECT are the
following:

·             The number and the order of
the columns must be the same in all queries.

·             The data types must be
compatible.
The syntax is as
follows:
[SQL Statement
1]
INTERSECT
[SQL Statement
2]

 
SELECT C1,C2 FROM T1
INTERSECT
SELECT C1,C2 FROM T2
Result:




 


C1


C2




1


A


B




2


A


C





Note:
INTERSECT
will work only in SQL 2005.


SQL
EXCEPT
The
EXCEPT (MINUS) operates on two
SQL statements. It takes
all the results from the first SQL statement, and then subtract out the ones
that are present in the second SQL statement to get the final answer. If the
second SQL statement includes results not present in the first SQL statement,
such results are ignored.

EXCEPT returns
any distinct values from the left query that are not also found on the right
query.

The basic rules
for combining the result sets of two queries that use EXCEPT are the
following:

·             The number and the order of
the columns must be the same in all queries.

·             The data types must be
compatible.
The syntax is as
follows:
[SQL Statement
1]
EXCEPT
[SQL Statement
2]
 
 
SELECT C1,C2 FROM T1
EXCEPT
SELECT C1,C2 FROM T2
 
Result:




 


C1


C2




 
 


		</summary>
	</entry>
		<entry>
		<title>
			SQL Parse Array Function
		</title>
		<link href="http://sscheral.atwiki.com/page/SQL%20Parse%20Array%20Function" />
		

		<id>@wiki::39/</id>
		<published>
			2007-09-27
			
		</published>
		<updated>
			2007-09-27T11:46:14Z
		</updated>
		
		
				
		<summary>
			

Yet another version of the function to return a table from a delimitted string of values


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[fn_ParseCSVString]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[fn_ParseCSVString]
GO


create function fn_ParseCSVString
(
@CSVString       varchar(8000) ,
@Delimiter varchar(10)
)
returns @tbl table (s varchar(1000))
as
/*
select * from dbo.fn_ParseCSVString ('qwe,c,rew,c,wer', ',c,')
*/
begin
declare @i int ,
 @j int
    select  @i = 1
    while @i &amp;lt;= len(@CSVString)
    begin
             select  @j = charindex(@Delimiter, @CSVString, @i)
                if @j = 0
         begin
                     select  @j = len(@CSVString) + 1
          end
               insert  @tbl select substring(@CSVString, @i, @j - @i)
            select  @i = @j + len(@Delimiter)
 end
       return
end

		</summary>
	</entry>
		<entry>
		<title>
			Operators T-SQL:
		</title>
		<link href="http://sscheral.atwiki.com/page/Operators%20T-SQL%3A" />
		

		<id>@wiki::38/</id>
		<published>
			2007-09-26
			
		</published>
		<updated>
			2007-09-26T07:16:05Z
		</updated>
		
		
				
		<summary>
			
Operators (T-SQL)
An operator is a symbol specifying an action that is performed on one or
more expressions. Microsoft® SQL Server™ uses these operator categories:

Arithmetic operators
Assignment operator
Bitwise operators
Comparison operators
Logical operators
String concatenation operator
Unary operators

Arithmetic Operators
Arithmetic operators perform mathematical operations on two expressions of
any of the data types of the numeric data type category. For more information
about data type categories, see Transact-SQL Syntax Conventions.



Operator
Meaning


+
(Add)
Addition.


-
(Subtract)
Subtraction.


*
(Multiply)
Multiplication.


/
(Divide)
Division.


%
(Modulo)
Returns the integer remainder of a division. For example, 12 %
5 = 2 because the remainder of 12 divided by 5 is 2.



 
The + and - operators can also be used to perform arithmetic operations on
datetime and smalldatetime values.
For information about the precision and scale of the result of an arithmetic
operation, see Precision,
Scale, and Length.
Assignment Operator
Transact-SQL has one assignment operator, the equals sign (=). In this
example, the @MyCounter variable is created. Then, the
assignment operator sets @MyCounter to a value returned by an
expression.
DECLARE @MyCounter INT
SET @MyCounter = 1
  
The assignment operator (=) can also be used to establish the relationship
between a column heading and the expression defining the values for the column.
This example displays two column headings named
FirstColumnHeading and SecondColumnHeading.
The string xyz is displayed in the FirstColumnHeading column
heading for all rows. Then, each product ID from the Products
table is listed in the SecondColumnHeading column heading.
USE Northwind
GO
SELECT FirstColumnHeading = 'xyz',
       SecondColumnHeading = ProductID
FROM Products
GO
  
Bitwise Operators
Bitwise operators perform bit manipulations between two expressions of any
of the data types of the integer data type category.



Operator
Meaning


&amp;amp;
(Bitwise AND)
Bitwise AND (two operands).


|
(Bitwise OR)
Bitwise OR (two operands).


^
(Bitwise Exclusive OR)
Bitwise exclusive OR (two operands).



 
The operands for bitwise operators can be any of the data types of the
integer or binary string data type categories (except for the
image data type), with the exception that both operands cannot
be any of the data types of the binary string data type category. The table
shows the supported operand data types.



Left operand
Right operand


binary
int, smallint, or
tinyint


bit
int, smallint,
tinyint, or bit


int
int, smallint,
tinyint, binary, or
varbinary


smallint
int, smallint,
tinyint, binary, or
varbinary


tinyint
int, smallint,
tinyint, binary, or
varbinary


varbinary
int, smallint, or
tinyint



 
Comparison Operators
Comparison operators test whether or not two expressions are the same.
Comparison operators can be used on all expressions except expressions of the
text, ntext, or image data
types.



Operator
Meaning


=
(Equals)
Equal to.


&amp;gt;
(Greater Than)
Greater than.


&amp;lt;
(Less Than)
Less than.


&amp;gt;=
(Greater Than or Equal To)
Greater than or equal to.


&amp;lt;=
(Less Than or Equal To)
Less than or equal to.


&amp;lt;&amp;gt; (Not Equal To)
Not equal to.


!=
(Not Equal To)
Not equal to (not SQL-92 standard).


!&amp;lt;
(Not Less Than)
Not less than (not SQL-92 standard).


!&amp;gt;
(Not Greater Than)
Not greater than (not SQL-92 standard).



 
The result of a comparison operator has the Boolean data type, which has
three values: TRUE, FALSE, and UNKNOWN. Expressions that return a Boolean data
type are known as Boolean expressions.
Unlike other SQL Server data types, a Boolean data type cannot be specified
as the data type of a table column or variable, and cannot be returned in a
result set.
When SET ANSI_NULLS is ON, an operator that has one or two NULL expressions
returns UNKNOWN. When SET ANSI_NULLS is OFF, the same rules apply, except an
equals operator returns TRUE if both expressions are NULL. For example, NULL =
NULL returns TRUE if SET ANSI_NULLS is OFF.
Expressions with Boolean data types are used in the WHERE clause to filter
the rows that qualify for the search conditions and in control-of-flow language
statements such as IF and WHILE, for example:
USE Northwind
GO
DECLARE @MyProduct int
SET @MyProduct = 10
IF (@MyProduct &amp;lt;&amp;gt; 0)
    SELECT *
    FROM Products
    WHERE ProductID = @MyProduct
GO
  
Logical Operators
Logical operators test for the truth of some condition. Logical operators,
like comparison operators, return a Boolean data type with a value of TRUE or
FALSE.



Operator
Meaning


ALL
TRUE if all of a set of comparisons are TRUE.


AND
TRUE if both Boolean expressions are TRUE.


ANY
TRUE if any one of a set of comparisons are TRUE.


BETWEEN
TRUE if the operand is within a range.


EXISTS
TRUE if a subquery contains any rows.


IN
TRUE if the operand is equal to one of a list of
expressions.


LIKE
TRUE if the operand matches a pattern.


NOT
Reverses the value of any other Boolean operator.


OR
TRUE if either Boolean expression is TRUE.


SOME
TRUE if some of a set of comparisons are TRUE.



 
For more information about logical operators, see the specific logical
operator topic.
String Concatenation Operator
The string concatenation operator allows string concatenation with the
addition sign (+), which is also known as the string concatenation operator.
All other string manipulation is handled through string functions such as
SUBSTRING.
By default, an empty string is interpreted as an empty string in INSERT or
assignment statements on data of the varchar data type. In
concatenating data of either the varchar,
char, or text data types, the empty string is
interpreted as an empty string. For example, ‘abc’ + ‘‘ +
‘def’ is stored as ‘abcdef’. However, if the sp_dbcmptlevel
compatibility level setting is 65, empty constants are treated as a single
blank character and ‘abc’ + ‘‘ + ‘def’ is stored as ‘abc
def’. For more information about the interpretation of empty strings, see
sp_dbcmptlevel.
Unary Operators
Unary operators perform an operation on only one expression of any of the
data types of the numeric data type category.



Operator
Meaning


+
(Positive)
Numeric value is positive.


-
(Negative)
Numeric value is negative.


~
(Bitwise NOT)
Returns the ones complement of the number.



 
The + (Positive) and - (Negative) operators can be used on any expression of
any of the data types of the numeric data type category. The ~ (Bitwise NOT)
operator can be used only on expressions of any of the data types of the
integer data type category.
Operator Precedence
When a complex expression has multiple operators, operator precedence
determines the sequence in which the operations are performed. The order of
execution can significantly affect the resulting value.
Operators have these precedence levels. An operator on higher levels is
evaluated before an operator on a lower level:

+ (Positive), - (Negative), ~ (Bitwise NOT)
* (Multiply), / (Division), % (Modulo)
+ (Add), (+ Concatenate), - (Subtract)
=, &amp;gt;, &amp;lt;, &amp;gt;=, &amp;lt;=, &amp;lt;&amp;gt;, !=, !&amp;gt;, !&amp;lt; (Comparison
operators)
^ (Bitwise Exlusive OR), &amp;amp; (Bitwise AND), | (Bitwise OR)
NOT
AND
ALL, ANY, BETWEEN, IN, LIKE, OR, SOME
= (Assignment)

When two operators in an expression have the same operator precedence level,
they are evaluated left to right based on their position in the expression. For
example, in the expression used in the SET statement of this example, the
subtraction operator is evaluated before the addition operator.
DECLARE @MyNumber int
SET @MyNumber = 4 - 2 + 27
-- Evaluates to 2 + 27 which yields an expression result of
29.
SELECT @MyNumber
  
Use parentheses to override the defined precedence of the operators in an
expression. Everything within the parentheses is evaluated first to yield a
single value before that value can be used by any operator outside of the
parentheses.
For example, in the expression used in the SET statement of this example,
the multiplication operator has a higher precedence than the addition operator,
so it gets evaluated first; the expression result is 13.
DECLARE @MyNumber int
SET @MyNumber = 2 * 4 + 5
-- Evaluates to 8 + 5 which yields an expression result of
13.
SELECT @MyNumber
  
In the expression used in the SET statement of this example, the parentheses
causes the addition to be performed first; the expression result is 18.
DECLARE @MyNumber int
SET @MyNumber = 2 * (4 + 5)
-- Evaluates to 2 * 9 which yields an expression result of
18.
SELECT @MyNumber
  
If an expression has nested parentheses, the most deeply nested expression
is evaluated first. This example contains nested parentheses, with the
expression 5 - 3 in the most deeply nested set of parentheses. This expression
yields a value of 2. Then, the addition operator (+) adds this result to 4,
which yields a value of 6. Finally, the 6 is multiplied by 2 to yield an
expression result of 12.
DECLARE @MyNumber int
SET @MyNumber = 2 * (4 + (5 - 3) )
-- Evaluates to 2 * (4 + 2) which further evaluates to 2 *
6, and
-- yields an expression result of 12.
SELECT @MyNumber
  
See Also
Functions

		</summary>
	</entry>
		<entry>
		<title>
			Pros &amp; Cons of Using SELECT, Views, and Stored Procedures in SQL Server
		</title>
		<link href="http://sscheral.atwiki.com/page/Pros%20%2526%20Cons%20of%20Using%20SELECT%2C%20Views%2C%20and%20Stored%20Procedures%20in%20SQL%20Server" />
		

		<id>@wiki::37/</id>
		<published>
			2007-09-26
			
		</published>
		<updated>
			2007-09-26T06:19:08Z
		</updated>
		
		
				
		<summary>
			
 Pros &amp;amp; Cons of Using SELECT, Views, and Stored Procedures in
SQL Server 
When I first started using SQL Server as a novice, I was initially
confused as to the differences between the SELECT statement, views, and stored
procedures. They all seemed to perform more or less the same task (retrieve
data), and I wanted to know the pros and cons of using each.
Why would SQL Server offer three different options to retrieve data from
database? As a developer and new DBA, I took it upon myself to learn everything
I could about these options, why they may be required, and when they should be
used. This article is a result of my learning and experience, and explains the
differences between SELECT statements, views, and stored procedures for the DBA
or developer new to SQL Server. I hope you find this article useful.
As you read this article, if you choose, you can cut and paste the code into
Query Analyzer I have provided in order to more fully understand and appreciate
the differences between the SELECT statement, views, and stored procedures. I
have divided this article into three parts to better explain this
information.
 
Starting Notes
To get us started on learning the differences between the SELECT statement,
views, and stored procedures, I need to mention the syscacheobjects system
table. It is used to store information about compiled objects and their
execution plans. The reason for this is because compiled SELECT statements,
views, and stored procedures are stored here, and I have used this table to
experiment and learn more about how these three different objects are stored
and used by SQL Server. If you are not familiar with this system table, you
might want to take a peek at it. It is stored in the master database, and can
be viewed with Enterprise Manager or Query Analyzer.
If you choose to follow along with the examples in this article, you will want
to run the DBCC FREEPROCCACHE command before each run. This command clears the
syscacheobjects table of any current cached objects, and allows us to perform
more accurate tests.
Now, let’s create a table and input a few rows in the table before we commence
at taking a look at the  differences between the SELECT statement, views, and
stored procedures.
 
Create Sample Table
I assume you have a database you can use for this. If not, you will want to
create one at this time. Now, we need to create a table for our
experimentation.
Create Table DummyTable1
(
             EmpId Int,
             EmpName Varchar(8000)
)
Now, let’s add a few records in this table using this script:
Insert Into DummyTable1 Values (1, Replicate ('a',20))
GO
Insert Into DummyTable1 Values (2, Replicate ('b',20))
GO
Insert Into DummyTable1 Values (3, Replicate ('c',20))
GO
Insert Into DummyTable1 Values (4, Replicate ('d',20))
GO
Insert Into DummyTable1 Values (5, Replicate ('e',20))
GO
Insert Into DummyTable1 Values (6, Replicate ('f',20))
GO
Insert Into DummyTable1 Values (7, Replicate ('g',20))
GO
Insert Into DummyTable1 Values (8, Replicate ('h',20))
GO
Insert Into DummyTable1 Values (9, Replicate ('i',20))
GO
Insert Into DummyTable1 Values (10, Replicate ('j',20))
GO
 
DummyTable1 has contains sufficient rows to experiment with the differences
between the SELECT statement, views, and stored procedures.
Let us begin with the SELECT statement and see how it is different from views
and stored procedures.
 
SELECT Statement
Now, let’s view the contents of the table by EXECuting the following command in
Query Analyzer for our new table.
SELECT EmpId, EmpName FROM DummyTable1
GO
EmpID EmpName
1 aaaaaaaaaaaaaaaaaaaa
2 bbbbbbbbbbbbbbbbbbbb
3 cccccccccccccccccccc
4 dddddddddddddddddddd
5 eeeeeeeeeeeeeeeeeeee
6 ffffffffffffffffffff
7 gggggggggggggggggggg
8 hhhhhhhhhhhhhhhhhhhh
9 iiiiiiiiiiiiiiiiiiii
10 jjjjjjjjjjjjjjjjjjjj
As you would expect, the data we inserted earlier has been displayed.
Now, let’s execute the following commands to clear the cache.
DBCC FREEPROCCACHE
GO
Freeing the procedure cache prevents an ad-hoc SQL statement from being reused,
assuming that it is currently in the cache. This means that the next time we
run the same ad-hoc statement, that it must be newly recompiled.
Now, let’s execute the following commands to display the data and cache
information for the table we created and that is now stored in SQL Server’s
syscacheobjects system table.
SELECT EmpId, EmpName FROM DummyTable1
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.syscacheobjects
GO
The result will display many columns, but we are only interested in four of
them, as shown below.
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 1 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Compiled Plan 2 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Here’s what the information displayed means:
Cacheobjtype: The type of object stored in the cache, which can include:
• Compiled Plan
• Executable Plan
• Parse Tree
• Cursor Parse Tree
• Extended Stored Procedure
We will be concentrating mainly on the Compiled Plan and the Executable Plan
cacheobjtype type objects.
Refcounts: Number of other cache objects referencing this cache object. A count
of 1 is the base.
Usecounts: Number of times this cache object has been used since inception.
Sql: Text of the statement.
Now, let’s execute the same SELECT statement:
SELECT EmpId, EmpName FROM DummyTable1
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Compiled Plan 2 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
The value of Usecounts has been incremented. SQL Server has used the same
compiled plan for the SELECT statement and incremented the Usecounts of the
executable plan. N number user will use the same compiled plan when we execute
the same SELECT statement.
Now, let us add a ‘WHERE’ clause on the SELECT statement and see the result
from the master.dbo.Syscacheobjects.
SELECT EmpId, EmpName FROM DummyTable1 WHERE EmpId = 5
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
SQL Server has not used the existing cache plan because of the change in the
SELECT statement. SQL Server will generate a new cache plan for the SELECT
statement along with old cache plan.
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 1 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Executable Plan 1 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Compiled Plan 2 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Let us execute the same SELECT statement with a different empid and verify the
result.
SELECT EmpId, EmpName FROM DummyTable1 WHERE EmpId = 3
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Executable Plan 1 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Compiled Plan 2 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Though we have given different empid values, SQL Server has used the same
compiled plan for the SELECT statement, and incremented the Usecounts of the
executable plan.
SQL Server has used the same compiled plan for the SELECT statement and
incremented the Usecounts of the executable plan. Different user will execute
the SELECT statement with different empid values, but will use the same
compiled plan and increase the Usecounts value of the executable plan.
Now, let’s execute the same statement with the username on the SELECT statement
and verify the results.
SELECT EmpId, EmpName FROM dbo.DummyTable1 WHERE EmpId = 3
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Executable Plan 1 1 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[DummyTable1] WHERE [EmpId]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[DummyTable1] WHERE [EmpId]=@1
Executable Plan 1 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Compiled Plan 2 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Now, we have two more rows in the cache plan because we have used different
usernames in the SELECT statements. SQL Server will generate a new compiled and
execution plan for different users. The same user will execute the SELECT
statement more than one time will use the same compiled plan and only increase
the Usecounts value of the executable plan.
Let us execute the same SELECT statement with different empid and verify the
results.
SELECT EmpId, EmpName FROM dbo.DummyTable1 WHERE EmpId = 3
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Executable Plan 1 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[DummyTable1] WHERE [EmpId]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[DummyTable1] WHERE [EmpId]=@1
Executable Plan 1 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Compiled Plan 2 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Now, let’s execute the same statement with the databasename and username on the
SELECT statement and view the results.
SELECT EmpId, EmpName FROM vijay.dbo.DummyTable1 WHERE EmpId = 3
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Executable Plan 1 1 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[vijay].[dbo].[DummyTable1] WHERE [EmpId]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[vijay].[dbo].[DummyTable1] WHERE [EmpId]=@1
Executable Plan 1 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[DummyTable1] WHERE [EmpId]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[DummyTable1] WHERE [EmpId]=@1
Executable Plan 1 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Compiled Plan 2 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
As a DBA or developer, we can minimize the creation of compilation plans if we
add the databasename, username, and WHERE condition for a SELECT statement.
Don’t change the combination of the SELECT statement to allow creating a new
execution plan unless it is really required. If you do, it will create a new
execution plan on the SELECT statement. We can minimize the execution plan to
upgrade the system’s performance.
Now, let’s execute the following commands to clear the cache before the
stored procedure experiment.
DBCC FREEPROCCACHE
GO
 
Stored Procedures
We will create a stored procedure with one parameter, and see how it is differs
from the SELECT statement and views.
CREATE PROC spDummyTable1 (@EmpID Int) AS
SELECT EmpID, EmpName FROM DummyTable1 WHERE EmpID = @EmpID
Now, let’s execute the following commands to display the data and cache
information for the spDummyTable1 we created.
EXEC spDummyTable1 1
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 1 spDummyTable1
Compiled Plan 2 1 spDummyTable1
SQL Server displays the compiled and executable plan for the spDummyTable1
stored procedure.
Let us execute the same statement again and see the cache details.
EXEC spDummyTable1 1
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 2 spDummyTable1
Compiled Plan 2 1 spDummyTable1
The value of Usecounts has been incremented. SQL Server has used the same
compiled plan for the SELECT statement and incremented the Usecounts of the
executable plan. N number user will use the same compiled plan when we execute
the same stored procedure.
Let’s execute the same stored procedure with a different empid parameter value
and view the cache details.
EXEC spDummyTable1 3
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 3 spDummyTable1
Compiled Plan 2 1 spDummyTable1
The value of Usecounts has been incremented. Though, we have given different
empid value, SQL Server has used the same compiled plan for the stored
procedure and incremented the Usecounts of the executable plan.
Now, let us execute the same stored procedure with the username and see the
cache details.
EXEC dbo.spDummyTable1 5
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 4 spDummyTable1
Compiled Plan 2 1 spDummyTable1
No difference at all. SQL Server has used the same compiled plan for the stored
procedure and incremented the Usecounts of the executable plan.
Let’s execute the same stored procedure from different user. I have created a
new user, called ‘user1,’ and given ‘Exec’ permission for spDummyTable1 stored
procedure. I have opened new Query Analyzer and connected using UID : user1;
PWD : user1. I have EXECuted the following command.
EXEC dbo.spDummyTable1 3
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Different users will execute the stored procedure with different or same empid
value and will use the same compiled plan and increase the Usecounts value of
the executable plan.
Now, let’s execute the same stored procedure with the databasename and username
and see the cache details.
EXEC vijay.dbo.spDummyTable1 7
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 5 spDummyTable1
Compiled Plan 2 1 spDummyTable1
No difference at all. SQL Server has used the same compiled plan for the stored
procedure and incremented the Usecounts of the executable plan.
Overall, stored procedure will compile once and use the same compiled plan
and increment the Usecounts value of the executable plan. A stored procedure is
pre-loaded in memory for faster execution.  It will really augment your system
on performance base. This really shows us the importance of the stored
procedure as compared with the SELECT statement and views.
Now, let’s execute the following commands to clear the cache before the
upcoming view experiment.
DBCC FREEPROCCACHE
GO
 
Views
We will create a view and how it is differs from theSELECT statement and stored
procedures.
CREATE VIEW vwDummyTable1 AS
SELECT EmpID, EmpName FROM DummyTable1
GO
Now, let’s execute the following commands to display the data and cache
information for the vwDummyTable1 we created.
SELECT EmpId, EmpName from vwDummyTable1
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 1 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
Compiled Plan 2 2 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
SQL Server has displayed the compiled and executable plan for the spDummyTable1
stored procedure.
Let’s now execute the same statement again and view the cache details.
SELECT EmpId, EmpName from vwDummyTable1
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 2 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
Compiled Plan 2 2 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
The value of Usecounts has been incremented. SQL Server has used the same
compiled plan for the SELECT statement on the view and incremented the
Usecounts of the executable plan. N number user will use the same compiled plan
when we execute the same SELECT statement on view.
Now, let’s add a WHERE clauses on the view SELECT statement and view the
results from the master.dbo.Syscacheobjects.
SELECT EmpId, EmpName from vwDummyTable1 WHERE EmpID = 4
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
SQL Server has not used the existing cache plan because of change in the view’s
SELECT statement. SQL Server generates a new cache plan for the SELECT
statement on view along with old cache plan.
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 1 (@1 tinyint)SELECT EmpID, EmpName FROM [vwDummyTable1]
WHERE [EmpID]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT EmpID, EmpName FROM [vwDummyTable1] WHERE
[EmpID]=@1
Executable Plan 1 2 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
Compiled Plan 2 2 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
Let’s execute the same view SELECT statement with different empid and view the
results.
SELECT EmpId, EmpName FROM vwDummyTable1 WHERE EmpID = 8
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1] WHERE [EmpId]=@1
Executable Plan 1 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Compiled Plan 2 2 ()SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[DummyTable1]
Though we have given different empid value, SQL Server has used the same
compiled plan for the SELECT statement on the view and incremented the
Usecounts of the executable plan.
The value of Usecounts has been incremented. SQL Server has used the same
compiled plan for the SELECT statement on the view and incremented the
Usecounts of the executable plan. Different users will execute the SELECT
statement on view with different empid value will use the same compiled plan
and only increase the Usecounts value of the executable plan
Now, let’s execute the same statement on the view with the username on the
SELECT statement and verify the results.
SELECT EmpId, EmpName from dbo.vwDummyTable1 WHERE EmpID = 8
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Though we have given different empid value, SQL Server has used same cache
compiled plan and increased the Usecounts value on the Execution plan.
Now, let us execute the same statement with the username on the SELECT
statement and verify the results.
SELECT EmpId, EmpName from dbo.vwDummyTable1 WHERE EmpID = 8
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 1 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[vwDummyTable1] WHERE [EmpID]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[vwDummyTable1] WHERE [EmpID]=@1
Executable Plan 1 2 (@1 tinyint)SELECT EmpID, EmpName FROM [vwDummyTable1]
WHERE [EmpID]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT EmpID, EmpName FROM [vwDummyTable1] WHERE
[EmpID]=@1
Executable Plan 1 2 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
Compiled Plan 2 2 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
Now, we have two more rows in the cache plan because we have used different
usernames in the SELECT statement. SQL Server generates a new compiled and
Execution plan for different user. The same user will execute the SELECT
statement more than one time will use the same compiled plan and only increase
the Usecounts value of the executable plan
Let’s execute the same SELECT statement on view with different empid and verify
the result.
SELECT EmpId, EmpName from dbo.vwDummyTable1 WHERE EmpID = 6
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[vwDummyTable1] WHERE [EmpID]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[vwDummyTable1] WHERE [EmpID]=@1
Executable Plan 1 2 (@1 tinyint)SELECT EmpID, EmpName FROM [vwDummyTable1]
WHERE [EmpID]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT EmpID, EmpName FROM [vwDummyTable1] WHERE
[EmpID]=@1
Executable Plan 1 2 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
Compiled Plan 2 2 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
Now, let’s execute the same statement with the databasename and username on the
view SELECT statement and verify the results.
SELECT EmpId, EmpName from vijay.dbo.vwDummyTable1 WHERE EmpID = 10
GO
SELECT cacheobjtype, refcounts, usecounts, sql FROM
master.dbo.Syscacheobjects
GO
Cacheobjtype Refcounts Usecounts Sql
Executable Plan 1 1 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[vwDummyTable1] WHERE [EmpID]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[dbo].[vwDummyTable1] WHERE [EmpID]=@1
Executable Plan 1 2 (@1 tinyint)SELECT EmpID, EmpName FROM [vwDummyTable1]
WHERE [EmpID]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT EmpID, EmpName FROM [vwDummyTable1] WHERE
[EmpID]=@1
Executable Plan 1 1 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[vijay].[dbo].[vwDummyTable1] WHERE [EmpID]=@1
Compiled Plan 2 2 (@1 tinyint)SELECT [EmpId]=[EmpId],[EmpName]=[EmpName] FROM
[vijay].[dbo].[vwDummyTable1] WHERE [EmpID]=@1
Executable Plan 1 2 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
Compiled Plan 2 2 ()SELECT EmpID, EmpName FROM [vwDummyTable1]
We have seen that we can minimize the creation of compilation plans if we add
the database name, username, and WHERE condition for a SELECT statement or on a
view. If you do change these, then your code has to be recompiled, hurting your
system’s performance. So what is the difference between a SELECT statement and
a view in regards to performance?. Is there any difference at all? No, the
compiled and executable plans are same for both SELECT statement and view. But
one difference is that a view is stored (physically) in a database, while
SELECT statements are not. The advantage of a view is that it, in some cases,
allows the easier administration of object permissions. For example, you create
a view and provide a SELECT permission for certain set of users, but not
others, that only allows them to see certain columns in a table, but not all.
In most cases, if you don’t have this need from a security perspective, then
the use of views in unnecessary.

		</summary>
	</entry>
		<entry>
		<title>
			Cookies using javascript
		</title>
		<link href="http://sscheral.atwiki.com/page/Cookies%20using%20javascript" />
		

		<id>@wiki::36/</id>
		<published>
			2007-09-25
			
		</published>
		<updated>
			2007-09-25T11:02:05Z
		</updated>
		
		
				
		<summary>
			
Before you start using cookies,
there are a few things you should be aware of:
Cookie technology has been supported
correctly since Netscape Navigator 2.0. Internet Explorer users should,
however, only use cookie technology on platforms supporting Internet Explorer
4.0 or better, due to errors in the cookie-handling routines of earlier
versions.

Since cookies are stored on the user's
hard drive, you as the developer have very little control over them. If a user
decides to turn off cookie support in his or her browser, your cookies will
simply not be saved. Therefore, if data persistence is an important feature of
your Web site, have a backup plan (such as server-side cookies or sessions)
ready as well.

A single domain cannot set more than
twenty cookies. A single cookie cannot exceed 4 KB in size. The maximum number
of cookies that may be set is 300.
Now, with the caveats out of the way, let's take a look at the ingredients that
make up a cookie.
1. The first element in a cookie is
a &quot;name&quot; attribute. Here, the &quot;name&quot; is a string used to identify the cookie
(akin to a variable name), followed by the data to be stored in the cookie.
This variable-value pair is required; you can't bake a cookie without it. For
example,
&amp;lt;A href=&quot;mailto:email=me@some.domain.com&quot;&amp;gt;email=me@some.domain.com&amp;lt;/A&amp;gt;

2. A cookie can also contain an
&quot;expires&quot; attribute, which specifies how long the cookie is valid for. For
example,
expires=Fri, 30-Jan-2004 12:00:00
GMT

Setting this element to a date in the
past will usually cause the browser to delete the cookie.
3. You can also add a &quot;path&quot;
attribute to a cookie -- this states where the cookie may be accessed from on
the Web site. Most often, this is set to the server's document root
path=/

to ensure that the data in the cookie
is available to all the scripts on the site.
4. The &quot;domain&quot; attribute allows you
to set a domain name for the cookie. Again, this is optional, and might look
like this:
domain=somedomain.com

5. Finally, the &quot;secure&quot; attribute is a
Boolean flag indicating whether a secure HTTP connection is required between
the client and server to read the data in the cookie. Usually, this is toggled
off.
As noted previously, only the first
attribute is required; the rest are all optional. If you're using them,
remember to separate them with semi-colons, as in the example below:
document.cookie = &quot;name=Joe; path=/;
domain=my.site.com; secure&quot;;

Now, let's look at writing some code to
create a cookie.
It's not very difficult to create
custom cookie-handling code -– after all, all you're really doing is parsing
and manipulating a set of values in an encoded string. JavaScript makes it even
easier by exposing a &quot;document.cookie&quot; element that does most of the dirty work
for you; all you need to do is give it the cookie data to be written. Consider
the following example, which illustrates:
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;

&amp;lt;script language = &quot;JavaScript&quot;&amp;gt;
&amp;lt;!-- start hiding
function writeCookie()
{

// ask for input
var name = prompt(&quot;What's your name?&quot;, &quot;&quot;);

// set expiry date
var d = new Date(&quot;January 31, 2004&quot;);
var cd = d.toGMTString();

// set cookie parameters
var c = &quot;username=&quot; + escape(name) + &quot;;expires=&quot; + cd;

// write cookie
document.cookie = c;
}

// stop hiding --&amp;gt;
&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;

&amp;lt;body onLoad=&quot;writeCookie()&quot;&amp;gt;
&amp;lt;/body&amp;gt;

&amp;lt;/html&amp;gt;

Most of this is pretty simple: the
prompt() method takes care of popping up a box for user input, and the
corresponding value is encoded into the cookie string for storage. Similarly, a
Date object is instantiated with the cookie's expiry date, converted to the
requisite format using the Date object's toGMTString() method and the resulting
value is added to the cookie string as part of the expires attribute explained
earlier. Once the cookie string is ready, the document.cookie property takes
care of writing it to a file.
Now, try running the code above in
your browser. You should see an input box. Enter your name into the box. The
value you entered into the box should now be saved as a cookie to your hard
drive. If you're the suspicious type, verify this by looking in your browser's
cookies directory; you should see a cookie with contents like this:
username
Guru
localhost/cookies/
0
4249743488
29612272
2610381856
29612264
Now, that was pretty simple -- but
there's more than one way to skin a cat. If you're in a rush and don't have too
much time to spend on implementing a custom cookie library, the Web throws up a
number of interesting public-domain libraries which are powerful, stable and
easy to use.
The best-known of these
public-domain cookie libraries is the one created by Bill Dortch in 1996, and
used extensively in many sites on account of its rich features and overall
stability. Coincidentally, this is also the library I plan to use throughout
the rest of this tutorial, so drop by and download a copy before reading any
further.
Once you've got yourself a copy of
the library, copy it to your development area, and create the following simple
HTML document (remember to use the correct path to the library when linking to
it in the JavaScript tags):
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;script language=&quot;JavaScript&quot; src=&quot;cookieLibrary.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script language=&quot;JavaScript&quot; type=&quot;text/javascript&quot;&amp;gt;
function writeName()
{
// get user input from form field
var user = document.forms[0].elements[0].value;

// calculate expiry date 1 hour from now
var d = new Date();
d.setTime(d.getTime() + (60 * 60 * 1000));

// write value to cookie
SetCookie(&quot;username&quot;, user, d);
alert(&quot;Data written successfully&quot;);
}
&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;

&amp;lt;body&amp;gt;
&amp;lt;form&amp;gt;

Enter your name
&amp;lt;input type=&quot;text&quot; name=&quot;username&quot; size=&quot;10&quot;&amp;gt;
&amp;lt;input type=&quot;button&quot; onClick=&quot;javascript:writeName()&quot; value=&quot;Save!&quot;&amp;gt;
&amp;lt;/form&amp;gt;

&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

With the Bill Dortch library, setting a
cookie is as simple as calling the SetCookie() function with appropriate
arguments. The first two of these arguments are the mandatory name and value
parameters - these must be set for the cookie to be valid. For persistent
cookies, you would also follow these two arguments with an expiry date set to
60 minutes ahead of current time (60 minutes * 60 seconds * 1000 milliseconds);
this will ensure that the cookie is saved to the hard drive and remains valid
for 1 hour. For non-persistent (session) cookies, simply omit this expiry
date.
Here too, once you've entered your
name into the form and hit the
&quot;Save!&quot; button, your cookie will be saved to disk in your browser's cookies
directory. If you look at the code for the SetCookie() function, you'll see
that internally, it does pretty much the same thing you manually did in the
example on the previous page.
Now, that takes care of writing a cookie. But how about reading back the data
you stored in it?
Fortunately, the Bill Dortch library
has you covered on that front as well, with its GetCookie() function. To
illustrate, consider the following example, which checks for a cookie and
retrieves a value from it for display if available:
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;script language=&quot;JavaScript&quot; src=&quot;cookieLibrary.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script language=&quot;JavaScript&quot; type=&quot;text/javascript&quot;&amp;gt;
if (GetCookie(&quot;username&quot;))
{
alert(&quot;Welcome back, &quot; + GetCookie(&quot;username&quot;));
}
&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;

&amp;lt;body&amp;gt;
&amp;lt;/body&amp;gt;

&amp;lt;/html&amp;gt;

Here, when the page loads, the
GetCookie() function will check to see if a cookie named &quot;username&quot; exists on
the client for the specified domain/path combination. If it does, it will be
retrieved, the value stored within it will be read, and an alert box will be
shown with a welcome message.
Let's look at another example, this
one tracking the number of visits that the user has made to the particular Web
page:
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;script language=&quot;JavaScript&quot; src=&quot;cookieLibrary.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script language=&quot;JavaScript&quot;&amp;gt;

// check to see if cookie exists
// if not, this is first visit
if(GetCookie(&quot;visits&quot;) == null)
{
var visitCount = 1
}
// else this is second or greater visit
// retrieve last counted value and add 1
else
{
visitCount = parseInt(GetCookie(&quot;visits&quot;))+1
}

// set expiry date for 1 year from now
var d = new Date();
d.setDate(d.getDate() + 365);

// update cookie with new count
SetCookie(&quot;visits&quot;, visitCount, d);

// display visit counter
document.write(&quot;This is visit &quot; + visitCount)
&amp;lt;/script&amp;gt;

&amp;lt;/head&amp;gt;

&amp;lt;body&amp;gt;
&amp;lt;/body&amp;gt;

&amp;lt;/html&amp;gt;

Here, as before, I use an if test to
check whether a cookie already exists to track the number of visits. If it
does, I use the GetCookie() function to retrieve the value; if it does not, I
assume this is the first visit to the page and initialize the counter to 1. The
value of the counter is then updated (if necessary) and written back to the
cookie in readiness for the next visit.
So that takes care of writing
cookies, and then reading the values back. Now, how about a composite example
that you can actually use?
In this next example, I'll assume a
multi-lingual Web site, where the user has a choice of viewing the content in
either French or English. The first time the user visits the site, (s)he is
permitted to select one of the two languages. This choice is stored in a
cookie, so that on the next visit, the client is automatically redirected to
the chosen language without requiring the user to re-select a
language.
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;script language=&quot;JavaScript&quot; src=&quot;cookieLibrary.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script language=&quot;JavaScript&quot;&amp;gt;
// check to see if cookie exists
// if yes, redirect to language page
if (GetCookie(&quot;lang&quot;) == &quot;EN&quot;)
{
document.location.href=&quot;index.en.html&quot;;
}
else if (GetCookie(&quot;lang&quot;) == &quot;FR&quot;)
{
document.location.href=&quot;index.fr.html&quot;;
}

// function to write selected language to cookie
function lang(l)
{
// set expiry date for 1 year from now
var d = new Date();
d.setDate(d.getDate() + 365);

// write cookie
SetCookie(&quot;lang&quot;, l, d);

// take user to appropriate language page
if (l == &quot;EN&quot;)
{
document.location.href=&quot;index.en.html&quot;;
}
else if (l == &quot;FR&quot;)
{
document.location.href=&quot;index.fr.html&quot;;
}

}
&amp;lt;/script&amp;gt;

&amp;lt;/head&amp;gt;

&amp;lt;body&amp;gt;

&amp;lt;h2&amp;gt;
Please select your language:
&amp;lt;ul&amp;gt;
&amp;lt;li&amp;gt;&amp;lt;a href=&quot;javascript:lang('EN');&quot;&amp;gt;English&amp;lt;/a&amp;gt;
&amp;lt;li&amp;gt;&amp;lt;a href=&quot;javascript:lang('FR');&quot;&amp;gt;French&amp;lt;/a&amp;gt;
&amp;lt;/ul&amp;gt;
&amp;lt;/h2&amp;gt;

&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

That was simple enough. When the user
visits the page, the code first checks to see if a cookie with the selected
language already exists. If it does, the browser is automatically redirected to
pages in that language. If no cookie exists, it implies that the user has not
selected a language, and so a language choice is displayed. The language
selected is then written to a cookie in preparation for the next
visit.
And that's about it for this
tutorial. Over the last few pages, I gave you a crash course in reading and
writing cookies using JavaScript. I explained what cookies were, dissected the
innards of a cookie and showed you what they contain, and then took you through
the process of reading and writing a cookie with the document.cookie property,
and with the Bill Dortch cookie library. Finally, I wrapped things up with an
example of how you could use cookies in a real-world environment, to
personalize a Web site for your users by automatically selecting their
favourite language for them.
Of course, this is just the tip of
the iceberg. You can do a lot more with cookies; take a look at the following
links for more information:
The Netscape cookie specification,
athttp://www.netscape.com/newsref/std/cookie_spec.html
Bill Dortch's cookie library,
athttp://www.webwoman.biz/articles/Cookies/cookie.txt
JavaScript cookie applications,
athttp://javascript.internet.com/cookies/
More sample cookie applications,
athttp://members.ozemail.com.au/~dcrombie/cookie.htmlandhttp://developer.netscape.com/viewsource/archive/goodman_cookies.html
Detecting cookie support in the
client, athttp://www.javascriptkit.com/javatutors/cookiedetect.shtml
Sample cookie code and demos,
athttp://www.cookiecentral.com/
Until next time, be good!

		</summary>
	</entry>
		<entry>
		<title>
			Asp common code
		</title>
		<link href="http://sscheral.atwiki.com/page/Asp%20common%20code" />
		

		<id>@wiki::35/</id>
		<published>
			2007-09-24
			
		</published>
		<updated>
			2007-09-24T07:14:07Z
		</updated>
		
		
				
		<summary>
			

Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports System.Data
Imports System.Security.Cryptography
Imports System
Imports System.IO
Imports System.Text
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.ComponentModel


Namespace All


    Public Class Choice
        Inherits QuestionChoice
        Public Sub New(ByVal Value As String, ByVal Text As String)
            MyBase.New(Value, Text)
        End Sub
    End Class


    Public Class ChoiceMatrix
        Private _Choice As ArrayList
        Private _ChoiceOptions As ArrayList
        Public Sub New()
            _Choice = New ArrayList
            _ChoiceOptions = New ArrayList
        End Sub
        Public Sub AddChoice(ByVal vChoice As Choice)
            _Choice.Add(vChoice)
        End Sub
        Public Sub AddChoiceOption(ByVal vChoiceOption As ChoiceOption)
            _ChoiceOptions.Add(vChoiceOption)
        End Sub
        Public Function Choices() As ArrayList
            Return _Choice
        End Function
        Public Function ChoiceOptions() As ArrayList
            Return _ChoiceOptions
        End Function
    End Class


    Public Class ChoiceMatrixWithSubOption
        Inherits Monkey.Survey.ChoiceMatrix
        Public Sub New()
            MyBase.New()
        End Sub
    End Class


    Public Class ChoiceOption
        Inherits QuestionChoice
        Private _subOptions As ArrayList
        Private _ChoiceControlType As ChoiceControlTypes
        Public Sub New(ByVal Value As String, ByVal Text As String, ByVal ChoiceControlType As ChoiceControlTypes)
            MyBase.New(Value, Text)
            _subOptions = New ArrayList
            _ChoiceControlType = ChoiceControlType
        End Sub
        Public Sub AddSubOption(ByVal SubOption As ChoiceSubOption)
            _subOptions.Add(SubOption)
        End Sub
        Public ReadOnly Property ChoiceSubOptions() As ArrayList
            Get
                Return _subOptions
            End Get
        End Property
        Public ReadOnly Property ChoiceControlType() As ChoiceControlTypes
            Get
                Return _ChoiceControlType
            End Get
        End Property


    End Class


    Public Enum ChoiceControlTypes
        CheckBox       '0
        RadioButton    '1
        DropDown       '2
        TextBox        '3
        ListBox        '4
        'ListBox        '2
        'DropDown       '3
        'TextBox        '4
    End Enum


    Public Class ChoiceSubOption
        Inherits QuestionChoice
        Public Sub New(ByVal Value As String, ByVal Text As String)
            MyBase.New(Value, Text)
        End Sub
    End Class


    Public Module clsAppFunctions
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand(&quot;&quot;, con)
        Dim strSQL As String


        Public Sub loadddlStatus(ByVal ddlstatus As DropDownList)


            With ddlstatus.Items
                .Insert(0, &quot;any status&quot;)
                .Insert(1, &quot;not sent&quot;)
                .Insert(2, &quot;sent&quot;)
                .Insert(3, &quot;responded&quot;)
                .Insert(4, &quot;declined&quot;)
            End With
        End Sub


        Public Sub loadDDLType(ByVal ddlType As DropDownList)
            With ddlType.Items
                .Clear()
                .Insert(0, &quot;EMail&quot;)
                .Insert(1, &quot;FirstName&quot;)
                .Insert(2, &quot;LastName&quot;)
            End With
        End Sub


        Public Sub loadDDLStartsWith(ByVal ddlStartsWith As DropDownList)
            With ddlStartsWith.Items
                .Clear()
                .Insert(0, &quot;starts with&quot;)
                .Insert(1, &quot;ends with&quot;)
                .Insert(2, &quot;contains&quot;)
                .Insert(3, &quot;equals&quot;)
            End With
            'ddlStartsWith.Items.Add(New ListItem(&quot;starts with&quot;, 0))
            'ddlStartsWith.Items.Add(New ListItem(&quot;ends with&quot;, 1))
            'ddlStartsWith.Items.Add(New ListItem(&quot;contains&quot;, 2))
            'ddlStartsWith.Items.Add(New ListItem(&quot;equals&quot;, 3))
        End Sub



        Public Function loadDDL(ByVal ddlload As DropDownList, ByVal con As SqlConnection, ByVal cmd As SqlCommand, ByVal strSQL As String)
            Dim i As Integer = 1
            Dim rd As SqlDataReader


            cmd = New SqlCommand(strSQL, con)
            ddlload.Items.Insert(0, &quot;Select&quot;)
            With cmd
                cmd.CommandType = Data.CommandType.Text
                rd = cmd.ExecuteReader
            End With


            While rd.Read
                ddlload.Items.Insert(i, rd(0))
                i = i + 1
            End While
            rd.Close()
            Return 1
        End Function


        Public Sub refreshGridViewWithDataAdapter(ByVal gridview1 As GridView, ByVal con As SqlConnection, ByVal strSql As String)


            Dim cmd As New SqlCommand
            Dim ad As SqlDataAdapter
            Dim ds As New System.Data.DataSet


            With cmd
                .CommandType = CommandType.Text
                .CommandText = strSql
                .Connection = con
            End With
            ad = New SqlDataAdapter(cmd)
            'ad.SelectCommand = cmd


            ad.Fill(ds)
            ' gridview1.DataSource = New DataSet(&quot;ds&quot;).Tables(0)
            If ds.Tables.Count &amp;lt;&amp;gt; 0 Then
                gridview1.DataSource = ds.Tables(0)
                gridview1.DataBind()
            Else
                gridview1.DataSource = Nothing
                gridview1.DataBind()
            End If


        End Sub



        Public Sub ExecuteQuery(ByVal con As SqlConnection, ByVal strSQL As String)
            Dim cmd As New SqlCommand(strSQL, con)
            cmd.CommandType = CommandType.Text
            cmd.ExecuteNonQuery()
        End Sub


        Public Function checkExists(ByVal con As SqlConnection, ByVal strSQL As String)
            Dim cmd As New SqlCommand(strSQL, con)
            Dim rd As SqlDataReader
            cmd.CommandType = CommandType.Text
            rd = cmd.ExecuteReader


            If rd.HasRows Then
                rd.Close()
                Return True
            Else
                rd.Close()
                Return False
            End If


        End Function


    End Module


    Public Enum ControlTypes
        RadioButtonList = 1
        CheckBoxList = 2
        ListBox = 3
        DropDown = 4
        TextBox = 5
        Label = 6
        MultipleTextBox = 7
        MultipleDropDown = 8
        Image = 9
        Calendar = 10
        Buttons = 11
        Matrix = 12
        FileUpload = 13
        NameAddressUS = 14
        NameAddressGeneral = 15
        'MatrixRadioButton = 12
        'MatrixCheckBox = 14
        'MatrixDropDown = 15


    End Enum


    Public Module ModCommonFunctions
        Public Const COMMA = &quot;,&quot;


        Public Function OpenConnection(ByVal c As SqlConnection) As SqlConnection
            c.ConnectionString = ConfigurationManager.AppSettings(&quot;connectionstring&quot;)
            If c.State = Data.ConnectionState.Closed Then
                c.Open()
            End If
            Return c
        End Function
        Public Sub CloseConnection(ByRef c As SqlConnection)
            If c.State = Data.ConnectionState.Open Then
                c.Close()
            End If
        End Sub
        Public Sub SetFocus(ByVal ctrlname As Control, ByVal Pagename As Page)


            Dim str As String
            Dim a As Integer = 0


            str = &quot;&amp;lt;script languauge=javascript&amp;gt;document.getElementById('&quot; &amp;amp; ctrlname.ID &amp;amp; &quot;').focus();&amp;lt;/script&amp;gt;&quot;


            Dim PgName As Page
            PgName = Pagename
            '  PgName.RegisterStartupScript(&quot;setfocus&quot;, str)
        End Sub


        '  Public Shared Sub checkSession(ByVal intUserID)
        Public Sub checkSession(ByVal intUserID)


            If CStr(intUserID) = &quot;&quot; Then
                HttpContext.Current.Response.Redirect(&quot;../home.aspx?expired=1&quot;)
            End If
        End Sub
        Public Function getDataSet(ByVal ds As System.Data.DataSet, ByVal sqlCmd As SqlCommand, ByVal strSql As String, ByVal sqlCon As SqlConnection) As System.Data.DataSet


            Dim da As New SqlDataAdapter
            sqlCmd = New SqlCommand(strSql, sqlCon)
            da = New SqlDataAdapter(sqlCmd)
            da.Fill(ds)


            Return ds
        End Function
        ' can be 192 or 128


        Public Function ConvertStringToBit(ByVal str) As Int32


            'Dim i As Integer


            If IsDBNull(str) = True Then
                'i = -1
                Return -1
                Exit Function
            End If


            'If str = True Then
            '    i = 1
            'Else
            '    i = 0
            'End If


            Return IIf(str = True, 1, 0)


        End Function
        Function ChangeNullToString(ByVal strValue) As String
            Dim strReturn As String


            If IsDBNull(strValue) = True Or IsNothing(strValue) = True Then
                strReturn = &quot;&quot;
            Else
                strReturn = strValue
            End If


            Return strReturn
        End Function
        Function ChangeNumberToNull(ByVal txtValue) As String
            Dim retStr As String


            If IsDBNull(txtValue) = True Or txtValue = &quot;&quot; Or IsNothing(txtValue) = True Then
                retStr = &quot;Null&quot;
            Else
                retStr = txtValue
            End If


            Return retStr
        End Function
        Function ChangeToNull(ByVal txtValue)


            If txtValue = &quot;&quot; Or IsDBNull(txtValue) = True Then
                txtValue = &quot;null&quot;
            Else
                txtValue = &quot;'&quot; &amp;amp; txtValue &amp;amp; &quot;'&quot;
            End If


            ChangeToNull = txtValue


        End Function
        Public Function NumbersOnly(ByVal Data As String) As String
            Dim strNumber As String = &quot;&quot;
            Try


                Dim blndigit As Boolean = False
                Dim I As Integer


                If IsDBNull(Data) = True Or Trim(Data) = &quot;&quot; Then
                    Return &quot;&quot;
                    Exit Function
                End If


                For I = 1 To Len(Data)
                    Select Case Mid(Data, I, 1)
                        Case &quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;
                            strNumber &amp;amp;= Mid(Data, I, 1)
                            'Case &quot;1&quot;
                            '    strNumber &amp;amp;= Mid(Data, I, 1)
                            'Case &quot;2&quot;
                            '    strNumber &amp;amp;= Mid(Data, I, 1)
                            'Case &quot;3&quot;
                            '    strNumber &amp;amp;= Mid(Data, I, 1)
                            'Case &quot;4&quot;
                            '    strNumber &amp;amp;= Mid(Data, I, 1)
                            'Case &quot;5&quot;
                            '    strNumber &amp;amp;= Mid(Data, I, 1)
                            'Case &quot;6&quot;
                            '    strNumber &amp;amp;= Mid(Data, I, 1)
                            'Case &quot;7&quot;
                            '    strNumber &amp;amp;= Mid(Data, I, 1)
                            'Case &quot;8&quot;
                            '    strNumber &amp;amp;= Mid(Data, I, 1)
                            'Case &quot;9&quot;
                            '    strNumber &amp;amp;= Mid(Data, I, 1)
                    End Select
                Next
                NumbersOnly = strNumber
                '  Return strNumber
            Catch ex As Exception
                Throw ex
                'MsgBox(ex.Message, MsgBoxStyle.Information)
            End Try


        End Function
        Public Function NumbersOnlyFound(ByVal Data As String) As Boolean


            Try


                Dim blnFound As Boolean = True
                Dim I As Integer


                If IsDBNull(Data) = True Or Trim(Data) = &quot;&quot; Then
                    Return &quot;&quot;
                    Exit Function
                End If


                For I = 1 To Len(Data)


                    Dim strVal As String


                    strVal = Mid(Data, I, 1)
                    If strVal = &quot;0&quot; Or strVal = &quot;1&quot; Or strVal = &quot;2&quot; Or strVal = &quot;3&quot; Or _
                       strVal = &quot;4&quot; Or strVal = &quot;5&quot; Or strVal = &quot;6&quot; Or strVal = &quot;7&quot; _
                       Or strVal = &quot;8&quot; Or strVal = &quot;9&quot; Then
                    Else
                        blnFound = False
                        Exit For
                    End If
                Next


                NumbersOnlyFound = blnFound


            Catch ex As Exception
                Throw ex
                'MsgBox(ex.Message, MsgBoxStyle.Information)
            End Try


        End Function
        Function ChangeToZero(ByVal txtValue)
            If IsDBNull(txtValue) Then
                txtValue = 0
            ElseIf CStr(txtValue) = &quot;&quot; Then
                txtValue = 0
            Else
                txtValue = txtValue
            End If
            ChangeToZero = txtValue
        End Function
        Function ChangeNumberToEmpty(ByVal txtValue)
            If IsDBNull(txtValue) Or txtValue = &quot;0&quot; Then
                txtValue = &quot;&quot;
            Else
                txtValue = txtValue
            End If
            ChangeNumberToEmpty = txtValue
            Return ChangeNumberToEmpty
        End Function
        ' Function ChangeToEmptySQLString(ByVal txtValue)
        '    If IsDBNull(txtValue) Or Trim(txtValue) = &quot;&quot; Then
        '       ChangeToEmptySQLString = &quot;''&quot;
        '  Else
        '     ChangeToEmptySQLString = txtValue
        ' End If
        ' End Function


        Function PrepareStringForDropDownList(ByVal strVariant As Object, Optional ByVal isValueAString As Boolean = False)


            '' will be used only when a string datatype is used for value in a drowdown box and 
            '' you want to return null for the first item as empty string or zero (as string)


            ' ''  NULL WILL BE RETURNED IF blnReturnNull = TRUE
            ' '' Emty quotes will be returned if blnreturnnull = false


            'Dim Str As String
            'Dim Strnull As System.DBNull


            ''      If blnReturnNull = True Then
            If Trim(strVariant) = &quot;&quot; Or Trim(strVariant) = &quot;0&quot; Then
                PrepareStringForDropDownList = &quot;Null&quot;
                Exit Function
            Else
                If isValueAString = True Then
                    PrepareStringForDropDownList = Quoted(Trim(strVariant))
                Else
                    PrepareStringForDropDownList = strVariant
                End If
            End If


            ''End If



            ''  If IsDBNull(strVariant) = True Or Trim(strVariant) = &quot;&quot; Then
            '' PrepareStringForDropDownList = &quot;''&quot;
            '' Else
            ''    Str = strVariant
            ''   PrepareStringForDropDownList = Quoted(Trim(Str))
            ''  End If
        End Function
        Function PrepareString(ByVal strVariant As Object, ByVal blnReturnNull As Boolean)


            ' NULL WILL BE RETURNED IF blnReturnNull = TRUE
            ' '' Emty quotes will be returned if blnreturnnull = false


            Dim Str As String
            Dim Strnull As System.DBNull = Nothing


            If blnReturnNull = True Then
                If IsDBNull(strVariant) = True Or Trim(strVariant) = &quot;&quot; Then
                    PrepareString = &quot;Null&quot;
                    Exit Function
                End If
            End If


            If IsDBNull(strVariant) = True Or Trim(strVariant) = &quot;&quot; Then
                PrepareString = &quot;''&quot;
            Else
                Str = strVariant
                PrepareString = Quoted(Trim(Str))
            End If
        End Function
        Function PrepareString(ByVal strVariant As Object)


            Dim Str As String


            If IsDBNull(strVariant) = True Or Trim(strVariant) = &quot;&quot; Then
                PrepareString = &quot;''&quot;
            Else
                Str = strVariant


                PrepareString = Quoted(Trim(Str))
            End If
        End Function
        Public Function Quoted(ByVal strToBeQuoted)
            Quoted = &quot;'&quot; &amp;amp; Replace(Trim(strToBeQuoted), &quot;'&quot;, &quot;''&quot;) &amp;amp; &quot;'&quot;
            Exit Function
        End Function
        Public Function PreparePwd(ByVal str As String)
            PreparePwd = &quot;'&quot; &amp;amp; Replace(str, &quot;'&quot;, &quot;''&quot;) &amp;amp; &quot;'&quot;
        End Function
        Public Function RemoveLastCharacter(ByVal str As String, ByVal LastChar As String) As String


            Dim strReturn As String
            str = Trim(str)


            If Right(str, 1) = LastChar Then
                strReturn = Left(str, Len(str) - 1)
            Else
                strReturn = str
            End If


            Return strReturn


        End Function


        Function ConvertToBit(ByVal val As Boolean) As Integer
            If val = True Then
                ConvertToBit = 1
            Else
                ConvertToBit = 0
            End If
        End Function
        Public Sub cleartextboxes(ByRef p As Page)
            Dim c As Control


            For Each c In p.Controls


                If c.GetType.ToString.Equals(&quot;System.Web.UI.WebControls.TextBox&quot;) Then
                    CType(c, TextBox).Text = &quot;&quot;
                End If


            Next
        End Sub
        Public Sub setlstValue(ByRef lst As ListBox, ByVal strValue As Object)


            If IsDBNull(strValue) = False Then
                lst.SelectedValue = strValue
            End If



        End Sub
        Public Sub RefreshGrid(ByRef dg As DataGrid, ByRef sqlcmd As SqlCommand, ByVal strSQL As String)


            Dim sqlReader As SqlDataReader


            With sqlcmd
                .CommandText = strSQL
                .CommandType = Data.CommandType.Text
                sqlReader = .ExecuteReader
            End With


            dg.DataSource = sqlReader


            dg.DataBind()
            sqlReader.Close()


        End Sub



        Public Function getSelectedFromList(ByRef lst As Object) As String
            Dim str As String = &quot;&quot;


            Dim i As Integer


            For i = 0 To (lst.Items.Count - 1)
                If (lst.Items(i).Selected) Then
                    str += lst.Items(i).Value &amp;amp; &quot;,&quot;
                End If
            Next


            If Len(str) &amp;gt; 0 Then str = Left(str, Len(str) - 1)


            Return str
        End Function
        Public Sub setOptListValue(ByRef opt As RadioButtonList, ByVal strValue As Object)


            Dim i As Integer


            i = ConvertStringToBit(strValue)


            If i &amp;lt;&amp;gt; -1 Then opt.SelectedValue = i


        End Sub



        Public Function ChangeDBNullToEmptyString(ByVal tStr As Object) As Object
            Dim str As String = &quot;&quot;
            If IsDBNull(tStr) = True Then
                Return str
            Else
                Return tStr
            End If
        End Function


        Public Function ChangeCboValueToDBNull(ByVal str As String) As Object


            If IsNothing(str) = True Or str = &quot;0&quot; Then
                Return DBNull.Value
            Else
                Return str
            End If


        End Function
        Public Function ChangetxtValueToDBNull(ByVal str As String, ByVal allowEmptyString As Boolean) As Object


            If allowEmptyString = False Then


                If IsNothing(str) = True Or str = &quot;&quot; Then
                    Return DBNull.Value
                Else
                    Return str
                End If


            Else


                If IsNothing(str) = True Then
                    Return DBNull.Value
                Else
                    Return str
                End If


            End If


        End Function
        ' Public Shared Function CreatePasswordChar(ByVal Intlen As Integer) As String
        Public Function CreatePasswordChar(ByVal Intlen As Integer) As String
            Dim I As Integer
            CreatePasswordChar = &quot;&quot;


            For I = 1 To Intlen
                CreatePasswordChar = CreatePasswordChar &amp;amp; &quot;*&quot;
            Next


            Return CreatePasswordChar
        End Function


        Public Sub ClearFields(ByVal parent As System.Web.UI.Control)
            Dim c As Control
            For Each c In parent.Controls
                If c.GetType() Is GetType(TextBox) Then
                    'is it a textbox?
                    Dim t As TextBox = c
                    t.Text = &quot;&quot;
                ElseIf c.GetType() Is GetType(HtmlControls.HtmlInputHidden) Then
                    'is it a hidden text?
                    Dim h As HtmlControls.HtmlInputHidden = c
                    h.Value = &quot;&quot;
                ElseIf c.GetType() Is GetType(DropDownList) Then
                    'is it a dropdown list?
                    Dim d As DropDownList = c
                    d.ClearSelection()
                ElseIf c.GetType() Is GetType(ListBox) Then
                    'is it a listbox?
                    Dim l As ListBox = c
                    l.ClearSelection()
                ElseIf c.GetType() Is GetType(RadioButtonList) Then
                    'is it a radiobutton list?
                    Dim rl As RadioButtonList = c
                    rl.ClearSelection()
                ElseIf c.GetType() Is GetType(CheckBox) Then
                    'is it a checkbox?
                    Dim chk As CheckBox = c
                    chk.Checked = False
                ElseIf c.GetType() Is GetType(CheckBoxList) Then
                    'is it a checkbox list?
                    Dim cl As CheckBoxList = c
                    cl.ClearSelection()
                End If
                If c.HasControls Then
                    ClearFields(c)
                End If
            Next
        End Sub
        Public Function GetColumnCaption(ByVal intfieldID As Long, ByVal intsurveyId As Long, ByVal intForWhichlstBox As Int16) As String
            Dim conn As New SqlConnection
            OpenConnection(conn)


            Dim columncaption As String


            '        Dim cmd As New SqlCommand(&quot;Exec GetQuestionText &quot; &amp;amp; ChangeToZero(intfieldID) &amp;amp; COMMA &amp;amp; ChangeToZero(intsurveyId), conn)
            Dim cmd As New SqlCommand(&quot;Exec GetQuestionText &quot; &amp;amp; ChangeToZero(intfieldID) &amp;amp; COMMA &amp;amp; ChangeToZero(intsurveyId) &amp;amp; COMMA &amp;amp; ChangeToZero(intForWhichlstBox), conn)
            cmd.CommandType = Data.CommandType.Text
            columncaption = cmd.ExecuteScalar


            If columncaption &amp;lt;&amp;gt; &quot;&quot; Then
                GetColumnCaption = columncaption
            Else
                GetColumnCaption = &quot;&quot;
            End If



        End Function


        'Public Sub GetEncryptedvalue(ByVal val As String)
        '    Dim i As Long
        '    If Len(val) &amp;gt; 0 And val.Trim &amp;lt;&amp;gt; &quot;&quot; Then
        '        Dim str As String
        '        str = &quot;&quot;
        '        For i = 1 To Len(val)
        '            If str = &quot;&quot; Then
        '                '  str=mid(
        '            End If
        '        Next
        '    End If
        'End Sub


        Public Sub SetError()
            HttpContext.Current.Session(&quot;errormsg&quot;) = HttpContext.Current.Server.GetLastError.GetBaseException.Message
        End Sub
        Public Function getRecordSet(ByRef sqlcmd As SqlCommand, ByVal strSQL As String) As SqlDataReader


            Dim sqlReader As SqlDataReader
            With sqlcmd
                .CommandText = strSQL
                .CommandType = Data.CommandType.Text
                sqlReader = .ExecuteReader()
            End With


            Return sqlReader


        End Function
        Public Function getSingleValue(ByRef sqlcmd As SqlCommand, ByVal strSQL As String) As String


            Dim str As String


            With sqlcmd
                .CommandText = strSQL
                .CommandType = Data.CommandType.Text
                str = ChangeDBNullToEmptyString(.ExecuteScalar)
            End With


            Return str


            sqlcmd.Parameters.Clear()
        End Function


        'for ins, upd, delete
        Public Sub runNonQuery(ByRef sqlcmd As SqlCommand, ByVal strSQL As String)


            With sqlcmd
                .CommandText = strSQL
                .CommandType = Data.CommandType.Text
                .ExecuteNonQuery()
            End With


        End Sub
        Public Sub CheckForSession() '' For Checking whether the session is expired or not
            If ChangeToZero(HttpContext.Current.Session(&quot;surveyId&quot;)) = 0 Then
                HttpContext.Current.Session.Abandon()
                HttpContext.Current.Response.Redirect(&quot;Home.aspx?reason=expired&quot;)
            End If
        End Sub
        Public Function IsFieldAsname(ByVal name As String) As Boolean
            IsFieldAsname = True
            Dim names, na, i, c
            names = name
            For Each na In names
                If Len(names) &amp;lt;= 0 Then
                    IsFieldAsname = False
                    Exit Function
                End If
            Next
            For i = 1 To Len(name)
                c = LCase(Mid(name, i, 1))
                If InStr(&quot;abcdefghijklmnopqrstuvwxyz_-.'&quot;, c) &amp;lt;= 0 Or IsNumeric(c) Then   'Chang    ed by Senthil on Aug26th
                    IsFieldAsname = False
                    Exit Function
                End If
            Next
        End Function
        Public Function IsValidEmail(ByVal email As String) As Boolean
            IsValidEmail = True
            Dim names, name, i, c
            names = Split(email, &quot;@&quot;)
            If UBound(names) &amp;lt;&amp;gt; 1 Then
                IsValidEmail = False
                Exit Function
            End If
            For Each name In names
                If Len(name) &amp;lt;= 0 Then
                    IsValidEmail = False
                    Exit Function
                End If
                For i = 1 To Len(name)
                    c = LCase(Mid(name, i, 1))
                    If InStr(&quot;abcdefghijklmnopqrstuvwxyz_-.'&quot;, c) &amp;lt;= 0 And Not IsNumeric(c) Then  'Changed by Senthil on Aug26th
                        IsValidEmail = False
                        Exit Function
                    End If
                Next
                If Left(name, 1) = &quot;.&quot; Or Right(name, 1) = &quot;.&quot; Then
                    IsValidEmail = False
                    Exit Function
                End If
                If Left(name, 1) = &quot;'&quot; Or Right(name, 1) = &quot;'&quot; Then  'New validation Added by senthil on Aug 26th 
                    IsValidEmail = False
                    Exit Function
                End If


            Next
            If InStr(names(1), &quot;.&quot;) &amp;lt;= 0 Then
                IsValidEmail = False
                Exit Function
            End If
            i = Len(names(1)) - InStrRev(names(1), &quot;.&quot;)
            If i &amp;lt;&amp;gt; 2 And i &amp;lt;&amp;gt; 3 Then
                IsValidEmail = False
                Exit Function
            End If
            If InStr(email, &quot;..&quot;) &amp;gt; 0 Then
                IsValidEmail = False
            End If
        End Function
        Public Function IsValidURL(ByVal Url As String) As Boolean
            IsValidURL = True
            Dim names, name, i, c
            names = Split(Url, &quot;://&quot;)
            If UBound(names) &amp;lt;&amp;gt; 1 Then
                IsValidURL = False
                Exit Function
            End If
            For Each name In names
                If Len(name) &amp;lt;= 0 Then
                    IsValidURL = False
                    Exit Function
                End If
                For i = 1 To Len(name)
                    c = LCase(Mid(name, i, 1))
                    If InStr(&quot;abcdefghijklmnopqrstuvwxyz_-.'&quot;, c) &amp;lt;= 0 And Not IsNumeric(c) Then
                        IsValidURL = False
                        Exit Function
                    End If
                Next
                If Left(name, 1) = &quot;.&quot; Or Right(name, 1) = &quot;.&quot; Then
                    IsValidURL = False
                    Exit Function
                End If
                If Left(name, 1) = &quot;'&quot; Or Right(name, 1) = &quot;'&quot; Then  'New validation Added by senthil on Aug 26th 
                    IsValidURL = False
                    Exit Function
                End If


            Next
            If InStr(names(1), &quot;.&quot;) &amp;lt;= 0 Then
                IsValidURL = False
                Exit Function
            End If
            i = Len(names(1)) - InStrRev(names(1), &quot;.&quot;)
            If i &amp;lt;&amp;gt; 2 And i &amp;lt;&amp;gt; 3 Then
                IsValidURL = False
                Exit Function
            End If
            If InStr(Url, &quot;..&quot;) &amp;gt; 0 Then
                IsValidURL = False
            End If
        End Function
        Public Function GetModuleName(ByVal intModId As Integer) As String
            Dim strsql As String = &quot;&quot;
            Dim sqlcmd As SqlCommand = Nothing


            strsql = &quot;Exec GetModuleName &quot; &amp;amp; Convert.ToString(intModId)
            With sqlcmd
                .CommandText = strsql
                .CommandType = Data.CommandType.Text
                GetModuleName = .ExecuteScalar
                .Parameters.Clear()
            End With


        End Function
        Function AuthenticateUser() As Boolean


            If HttpContext.Current.Session(&quot;UserID&quot;) Is Nothing Then Return False
            Return True


        End Function
    End Module


    Public Module modFillList


        Public Sub FillList(ByRef chklst As CheckBoxList, ByRef cmd As SqlCommand, ByVal strSQL As String, ByVal strValue As String, ByVal strText As String)


            Dim sqlReader As SqlDataReader


            With cmd
                .CommandText = strSQL
                sqlReader = .ExecuteReader
                .CommandType = CommandType.Text
            End With



            With chklst
                .DataSource = sqlReader
                .DataValueField = strValue
                .DataTextField = strText
                .DataBind()
            End With


            sqlReader.Close()
            cmd.Parameters.Clear()


        End Sub


        Public Sub FillList(ByRef lst As ListBox, ByRef sqlcmd As SqlCommand, ByVal strSQL As String, ByVal strValue As String, ByVal strText As String, ByVal blnAddFirstRow As Boolean)


            Dim sqlReader As SqlDataReader


            With sqlcmd
                .CommandText = strSQL
                .CommandType = CommandType.Text
                sqlReader = .ExecuteReader


            End With


            With lst
                .DataSource = sqlReader
                .DataValueField = strValue
                .DataTextField = strText
                .DataBind()
            End With


            If blnAddFirstRow = True Then
                lst.Items.Insert(0, (New ListItem(&quot;Select One&quot;, 0)))
            End If


            sqlReader.Close()
            sqlcmd.Parameters.Clear()


        End Sub
        Public Sub FillList(ByRef lst As DropDownList, ByRef sqlcmd As SqlCommand, ByVal strSQL As String, ByVal strValue As String, ByVal strText As String, ByVal blnAddFirstRow As Boolean, Optional ByVal FirstItem As String = &quot;&quot;, Optional ByVal Val As Int16 = 0)


            Dim sqlReader As SqlDataReader


            With sqlcmd
                .CommandText = strSQL
                .CommandType = CommandType.Text
                sqlReader = .ExecuteReader


            End With


            With lst
                .DataSource = sqlReader
                .DataValueField = strValue
                .DataTextField = strText
                .DataBind()
            End With



            If blnAddFirstRow = True Then
                If Val = 1 Then
                    lst.Items.Insert(0, (New ListItem(&quot;&quot;, 0)))
                Else
                    If FirstItem = &quot;&quot; Then
                        lst.Items.Insert(0, (New ListItem(&quot;Select&quot;, 0)))
                    Else
                        lst.Items.Insert(0, (New ListItem(FirstItem, 0)))
                    End If
                End If


            End If


            sqlReader.Close()
            sqlcmd.Parameters.Clear()


        End Sub


        Public Sub FillList(ByRef rbutlst As RadioButtonList, ByRef cmd As SqlCommand, ByVal strSQL As String, ByVal strValue As String, ByVal strText As String, ByVal intSelValue As Integer)


            Dim sqlReader As SqlDataReader


            With cmd
                .CommandText = strSQL
                sqlReader = .ExecuteReader
                .CommandType = CommandType.Text


            End With


            'sqlReader.
            With rbutlst
                .DataSource = sqlReader
                .DataValueField = strValue
                .DataTextField = strText
                .DataBind()
            End With
            rbutlst.SelectedValue = intSelValue


            sqlReader.Close()
            cmd.Parameters.Clear()


        End Sub
        Public Sub FillList(ByRef chklst As CheckBoxList, ByRef cmd As SqlCommand, ByVal strSQL As String, ByVal strValue As String, ByVal strText As String, ByVal setvalues As Boolean)


            Dim sqlReader As SqlDataReader


            With cmd
                .CommandText = strSQL
                sqlReader = .ExecuteReader
                .CommandType = CommandType.Text


            End With


            With sqlReader
                While .Read()
                    Dim stritemvalue, stritemtext
                    stritemvalue = sqlReader.Item(strValue)
                    stritemtext = sqlReader(strText)
                    chklst.Items.Add(New ListItem(.Item(strText), .Item(strValue)))
                    'If System.Convert.ToBoolean(.Item(2)) = True Then
                    '    chklst.Items.FindByValue(.Item(0)).Selected = True
                    'End If
                End While


            End With


            sqlReader.Close()


            cmd.Parameters.Clear()


        End Sub
        Public Function checkBox(ByRef c As CheckBox) As Integer
            Dim int As Integer
            If c.Checked = True Then
                int = 1
            Else
                int = 0
            End If
        End Function
    End Module


    Public Class QuestionChoice
        Private _Value As String
        Private _Text As String
        Public Sub New(ByVal Value As String, ByVal Text As String)
            _Value = Value
            _Text = Text
        End Sub
        Public ReadOnly Property Value() As String
            Get
                Return _Value
            End Get
        End Property
        Public ReadOnly Property Text() As String
            Get
                Return _Text
            End Get
        End Property
    End Class


    Public Class ReportQuestion
        Dim _questionText As String
        Dim _questionNo As String
        Public Property QuestionText() As String
            Get
                Return _questionText
            End Get
            Set(ByVal value As String)
                _questionText = value
            End Set
        End Property
        Public Property QuestionNo() As Integer
            Get
                Return _questionNo
            End Get
            Set(ByVal value As Integer)
                _questionNo = value
            End Set
        End Property



    End Class


    Public Class SubColumnInfo
        Public Sub New(ByVal Value As String, ByVal Text As String)
            'MyBase.New(Value, Text)
        End Sub


    End Class


    Public Class SubColumns
        Private _Value As String
        Private _Text As String
        Public Sub New(ByVal Value As String, ByVal Text As String)
            _Value = Value
            _Text = Text
        End Sub
        Public ReadOnly Property Value() As String
            Get
                Return _Value
            End Get
        End Property
        Public ReadOnly Property Text() As String
            Get
                Return _Text
            End Get
        End Property
    End Class


    Public Class RequiredFieldValidForCheckBoxLists
        Inherits System.Web.UI.WebControls.BaseValidator
        Private _listctrl As ListControl


        Public Sub New()
            MyBase.EnableClientScript = False
        End Sub


        Protected Overloads Overrides Function ControlPropertiesValid() As Boolean
            Dim ctrl As Control = FindControl(ControlToValidate)
            If Not (ctrl Is Nothing) Then
                _listctrl = CType(ctrl, ListControl)
                Return (Not (_listctrl Is Nothing))
            Else
                Return False
            End If
        End Function


        Protected Overloads Overrides Function EvaluateIsValid() As Boolean
            Return Not (_listctrl.SelectedIndex = -1)
        End Function
    End Class


    Public Class ValidatiorchkBoxLst
        Inherits System.Web.UI.WebControls.BaseValidator


        Protected Overrides Function ControlPropertiesValid() As Boolean
            Return True
        End Function


        Protected Overrides Function EvaluateIsValid() As Boolean
            ' Return this.EvaluateIsChecked()
            Return EvaluateIsChecked()


        End Function
        Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
            '  If MyBase.EnableClientScript Then
            If EnableClientScript Then
                'this.clientscript()
                ClientScript()
            End If
            MyBase.OnPreRender(e)
        End Sub


        Protected Function EvaluateIsChecked() As Boolean
            Dim _cbl As CheckBoxList
            _cbl = CType(FindControl(ControlToValidate), CheckBoxList)


            Dim li As ListItem
            For Each li In _cbl.Items
                If li.Selected = True Then
                    Return True
                End If
            Next
            Return False
        End Function
        Protected Sub ClientScript()
            MyBase.Attributes(&quot;evaluationfunction&quot;) = &quot;cb_verify&quot;
            Dim sb_Script As New StringBuilder
            sb_Script.Append(&quot;&amp;lt;script language='javascript'&amp;gt;&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;function cb_vefify(val) {&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;var val = document.all[document.all(\&quot;)
            sb_Script.Append(MyBase.ID)
            sb_Script.Append(&quot;\).controltovalidate);&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;var col = val.all;&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;if ( col != null ) {&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;for ( i = 0; i &amp;lt; col.length; i++ ) {&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;if (col.item(i).tagName == \'INPUT\') {&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;if ( col.item(i).checked ) {&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;return true;&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;}&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;}&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;}&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;return false;&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;}&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;}&quot;)
            sb_Script.Append(&quot;\r&quot;)
            sb_Script.Append(&quot;&amp;lt;/script&amp;gt;&quot;)
            'MyBase.Page.RegisterClientScriptBlock(&quot;RBLScript&quot;, sb_Script.ToString())
            MyBase.Page.ClientScript.RegisterClientScriptBlock(GetType(String), &quot;RBLScript&quot;, sb_Script.ToString)


        End Sub


    End Class


End Namespace

		</summary>
	</entry>
		<entry>
		<title>
			Rarely Used SQL Server functions
		</title>
		<link href="http://sscheral.atwiki.com/page/Rarely%20Used%20SQL%20Server%20functions" />
		

		<id>@wiki::34/</id>
		<published>
			2007-09-21
			
		</published>
		<updated>
			2007-09-21T13:06:23Z
		</updated>
		
		
				
		<summary>
			
 
BINARY_CHECKSUM
SIGN
COLUMNPROPERTY
DATALENGTH
ASCII, UNICODE
NULLIF
PARSENAME
STUFF
REVERSE
GETUTCDATE

BINARY_CHECKSUMBINARY_CHECKSUM
is handy if you want to check for data differences between 2 rows of data

In order to see what rows are in table 1 and not in table 2 and vice versa you
can do 2 left joins, 2 right joins or 1 left and 1 right join. To get the rows
that are different you can use BINARY_CHECKSUM. You have to run this example o
SQL Server 2000 to see it work, you can ofcourse use any tables just modify the
queries
Let’s get started…

--let's copy over 20 rows to a table named
authors2
SELECT TOP 20 * INTO tempdb..authors2
FROM pubs..authors

--update 5 records by appending X to the
au_fnameSET ROWCOUNT 5


UPDATE tempdb..authors2
SET au_fname =au_fname +'X'


--Set rowcount back to 0
SET ROWCOUNT 0

--let's insert a row that doesn't exist in
pubs
INSERT INTO tempdb..authors2
SELECT '666-66-6666', au_lname, au_fname, phone, address,
city, state, zip, contract
FROM tempdb..authors2
WHERE au_id ='172-32-1176'
--*** The BIG SELECT QUERY --***

--Not in PubsSELECT 'Does Not Exist On Production',t2.au_id
FROM pubs..authors t1
RIGHT JOIN tempdb..authors2 t2 ON t1.au_id =t2.au_id
WHERE t1.au_id IS NULL
UNION ALL
--Not in TempSELECT 'Does Not Exist In
Staging',t1.au_id
FROM pubs..authors t1
LEFT JOIN tempdb..authors2 t2 ON t1.au_id =t2.au_id
WHERE t2.au_id IS NULL
UNION ALL
--Data MismatchSELECT 'Data
Mismatch', t1.au_id
FROM( SELECT BINARY_CHECKSUM(*) AS CheckSum1 ,au_id FROM pubs..authors) t1
JOIN(SELECT BINARY_CHECKSUM(*) AS
CheckSum2,au_id FROM tempdb..authors2) t2
ON t1.au_id =t2.au_id
WHERE CheckSum1 &amp;lt;&amp;gt; CheckSum2

--Clean up
DROP TABLE tempdb..authors2
GO




SIGN Sometimes you
are asked by the front-end/middle-tier developers to return a rowcount as well
with the result set. However the developers want you to return 1 if there are
rows and 0 if there are none. How do you do such a thing?
Well I am going to show you two ways. the first way is by using CASE and
@@ROWCOUNT, the second way is by using the SIGN function

For CASE we will do this

RETURN CASE WHEN @@ROWCOUNT &amp;gt; 0 THEN 1 ELSE 0 END

So that's pretty simple, if @@ROWCOUNT is greater than 0 return 1 for
everything else return 0

Using the SIGN function is even easier, all you have to do is this

RETURN SIGN(@@ROWCOUNT)

That's all, SIGN Returns the positive (+1), zero (0), or negative (-1) sign of
the given expression. In this case -1 is not possible but the other two values
are
So let's see this in action


USE pubs
GO

--Case ProcCREATE PROCEDURE TestReturnValues
@au_id VARCHAR(49) ='172-32-1176'
AS
SELECT *
FROM authors
WHERE au_id =@au_id

RETURN CASE WHEN
@@ROWCOUNT &amp;gt; 0 THEN 1 ELSE 0
END
GO

--Sign Proc
CREATE PROCEDURE TestReturnValues2
@au_id VARCHAR(49) ='172-32-1176'
AS
SELECT *
FROM authors
WHERE au_id =@au_id

RETURN SIGN(@@ROWCOUNT)
GO


--Case Proc, 1 will be returned; default value is
used
DECLARE @Rowcount int
EXEC @Rowcount = TestReturnValues
SELECT @Rowcount
GO

--Case Proc, 0 will be returned; dummy value is
used
DECLARE @Rowcount int
EXEC @Rowcount = TestReturnValues 'ABC'
SELECT @Rowcount
GO

--Sign Proc, 1 will be returned; default value is
used
DECLARE @Rowcount int
EXEC @Rowcount = TestReturnValues2
SELECT @Rowcount
GO

--Sign Proc, 0 will be returned; dummy value is
used
DECLARE @Rowcount int
EXEC @Rowcount = TestReturnValues2
'ABC'
SELECT @Rowcount
GO


--Help the environment by recycling ;-)
DROP PROCEDURE
TestReturnValues2,TestReturnValues
GO


COLUMNPROPERTY
COLUMNPROPERTY is handy if you
need to find scale, precision, if it is an identity column and more. I have
listed all of them belowCREATE TABLE blah (ID DECIMAL(5,2) not null DEFAULT 99)
INSERT blah DEFAULT VALUES

SELECT * FROM blah
SELECT COLUMNPROPERTY( OBJECT_ID('blah'),'ID','AllowsNull')
AS AllowsNull,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','IsComputed')
AS IsComputed,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','IsCursorType') AS
IsCursorType,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','IsDeterministic') AS IsDeterministic,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','IsFulltextIndexed') AS IsFulltextIndexed,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','IsIdentity')
AS IsFulltextIndexed,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','IsIdNotForRepl') AS IsIdNotForRepl,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','IsIndexable')
AS IsIndexable,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','IsOutParam')
AS IsOutParam,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','IsPrecise')
AS IsPrecise,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','IsRowGuidCol') AS
IsRowGuidCol,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','Precision')
AS 'Precision',
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','Scale')
AS Scale,
COLUMNPROPERTY( OBJECT_ID('blah'),'ID','UsesAnsiTrim') AS
UsesAnsiTrim
FROM Blah


So what does all that stuff mean?

AllowsNull
Allows null values. 1 = TRUE
0 = FALSE
NULL = Invalid input

IsComputed
The column is a computed column. 1 = TRUE
0 = FALSE
NULL = Invalid input

IsCursorType
The procedure parameter is of type CURSOR. 1 = TRUE
0 = FALSE
NULL = Invalid input

IsDeterministic
The column is deterministic. This property applies only to computed columns and
view columns. 1 = TRUE
0 = FALSE
NULL = Invalid input. Not a computed column or view column.

IsFulltextIndexed
The column has been registered for full-text indexing. 1 = TRUE
0 = FALSE
NULL = Invalid input

IsIdentity
The column uses the IDENTITY property. 1 = TRUE
0 = FALSE
NULL = Invalid input

IsIdNotForRepl
The column checks for the IDENTITY_INSERT setting. If IDENTITY NOT FOR
REPLICATION is specified, the IDENTITY_INSERT setting is not checked. 1 =
TRUE
0 = FALSE
NULL = Invalid input

IsIndexable
The column can be indexed. 1 = TRUE
0 = FALSE
NULL = Invalid input

IsOutParam
The procedure parameter is an output parameter. 1 = TRUE
0 = FALSE
NULL = Invalid input

IsPrecise
The column is precise. This property applies only to deterministic columns. 1 =
TRUE
0 = FALSE
NULL = Invalid input. Not a deterministic column

IsRowGuidCol
The column has the uniqueidentifier data type and is defined with the
ROWGUIDCOL property. 1 = TRUE
0 = FALSE
NULL = Invalid input

Precision
Precision for the data type of the column or parameter. The precision of the
specified column data type
NULL = Invalid input

Scale
Scale for the data type of the column or parameter. The scale
NULL = Invalid input

UsesAnsiTrim
ANSI padding setting was ON when the table was initially created. 1= TRUE
0= FALSE
NULL = Invalid input




DATALENGTH Okay so
you know the LEN function but do you know the DATALENGTH function? There are
two major difference between LEN and DATALENGTH.
The first one deals with trailing spaces, execute the following code and you
will see that LEN returns 3 while DATALENGTH returns 4

DECLARE @V VARCHAR(50)
SELECT @V ='ABC '
SELECT LEN(@V),DATALENGTH(@V),@V

The second difference deals with unicode character data, as you know unicode
uses 2 bytes to store 1 character
Run the following example and you will see that LEN returns 3 while DATALENGTH
returns 6
DECLARE @V NVARCHAR(50)
SELECT @V ='ABC'
SELECT LEN(@V),DATALENGTH(@V),@V

If you do DATALENGTH(CONVERT(VARCHAR,@V)) you will get the same as LEN because
LEN does a RTRIM and converts to VARCHAR before returning



ASCII,
CHAR,UNICODEASCII will give you the ascii code for a
character so for A you will get 65
CHAR does the reverse of ascii CHAR(65) returns A
UNICODE will give you the unicode value for a character
NCHAR will give you the character for a unicode or ascii value
let's see how this works

SELECT ASCII('A'),CHAR(65),CHAR(ASCII('A')),
UNICODE(N'Λ'),NCHAR(923),NCHAR(UNICODE(N'Λ'))




NULLIFNULLIF
Returns a null value if the two specified expressions are equivalent.

Syntax
NULLIF ( expression , expression )

DECLARE @v VARCHAR(20)
SELECT @v = '
'

SELECT NULLIF(@v,' ')

You can combine NULLIF with COALESCE if you want to test for NULLS and Blanks
for example

DECLARE @v VARCHAR(20)
SELECT @v = '
'

SELECT COALESCE(NULLIF(@v,'
'),'N/A')


Here is another NULLIF example:
CREATE TABLE Blah (SomeCol VARCHAR(33))

INSERT Blah VALUES(NULL)
INSERT Blah VALUES('')
INSERT Blah VALUES(' ')
INSERT Blah VALUES('A')
INSERT Blah VALUES('B B')

--Using COALESCE and NULLIF
SELECT COALESCE(NULLIF(RTRIM(SomeCol),'
'),'N/A')
FROM Blah


--Using CASE
SELECT CASE WHEN
RTRIM(SomeCol) = '' THEN 'N/A'
WHEN RTRIM(SomeCol) IS
NULL THEN 'N/A'ELSE SomeCol END
SomeCol
FROM Blah


Output for both queries
-----------------------
N/A
N/A
N/A
A
B B


PARSENAME PARSENAME
retrieves parts of string delimited by dots. It is used to split
DataBaseServer, DataBaseName, ObjectOwner and ObjectName but you can use it to
split IP addresses, names etc

DECLARE @ParseString VARCHAR(100)
SELECT @ParseString = 'DataBaseServer.DataBaseName.ObjectOwner.ObjectName'

SELECT PARSENAME(@ParseString,4),
PARSENAME(@ParseString,3),
PARSENAME(@ParseString,2),
PARSENAME(@ParseString,1)


CREATE TABLE #Test (
SomeField VARCHAR(49))

INSERT INTO #Test
VALUES ('aaa-bbbbb')

INSERT INTO #Test
VALUES ('ppppp-bbbbb')

INSERT INTO #Test
VALUES ('zzzz-xxxxx')

--using PARSENAME
SELECT PARSENAME(REPLACE(SomeField,'-','.'),2)
FROM #Test



Another example:

CREATE TABLE BadData (FullName varchar(20) NOT NULL);
INSERT INTO BadData (FullName)
SELECT 'Clinton, Bill' UNION ALL
SELECT 'Johnson, Lyndon, B.' UNION ALL
SELECT 'Bush,
George, H.W.';

Split the names into 3 columns

Your output should be this:
LastName FirstName MiddleInitial
Clinton Bill
Johnson Lyndon B.
Bush George H.W.

SELECT FullName,PARSENAME(FullName2,NameLen+1) AS LastName,
PARSENAME(FullName2,NameLen) AS FirstName,
COALESCE(REPLACE(PARSENAME(FullName2,NameLen-1),'~','.'),'')
AS MiddleInitial
FROM(
SELECT LEN(FullName) -LEN(REPLACE(FullName,',','')) AS NameLen,
REPLACE(REPLACE(FullName,'.','~'),',
','.') AS FullName2,FullName
FROM BadData) x



STUFFSTUFF is
another function that is hardly used, it is useful if you want to replace or
add characters inside data
Take a look at the code below. the first STUFF will replace X with 98765, the
second STUFF will place 98765 before the X and the third stuff will replace X-
with 98765
DECLARE @v VARCHAR(11)
SELECT @v ='-X-'


SELECT STUFF(@v, 2, 1, '98765'),
STUFF(@v, 2, 0, '98765'),
STUFF(@v, 2, 2, '98765')


The STUFF function is very handy if you need to insert dashes in a social
security. You can accomplish that by using the function STUFF twice instead of
using substring,left and right

DECLARE @v VARCHAR(11)
SELECT @v ='123456789'

SELECT @v,STUFF(STUFF(@v,4,0,'-'),7,0,'-')



REVERSEREVERSE just reverses the
value, for example the code below returns CBA

SELECT REVERSE('ABC')

Reverse is handy if you need to split values, take a look at this example

CREATE TABLE #TestCityStateZip (csz
CHAR(49))
INSERT INTO #TestCityStateZip VALUES ('city ,st
12223')
INSERT INTO #TestCityStateZip VALUES ('New York City,NY
10028')
INSERT INTO #TestCityStateZip VALUES ('Princeton , NJ
08536')
INSERT INTO #TestCityStateZip VALUES ('Princeton,NJ
08536 ')
INSERT INTO #TestCityStateZip VALUES ('Long Island City,
NY 10013')
INSERT INTO #TestCityStateZip VALUES ('Long Island City,
NY 10013 ')
INSERT INTO #TestCityStateZip VALUES ('Long Island City
, NY 10013')
INSERT INTO #TestCityStateZip VALUES ('Long Island City
,NY 10013 ')


SELECT LEFT(csz,CHARINDEX(',',csz)-1)AS
City,
LEFT(LTRIM(SUBSTRING(csz,(CHARINDEX(',',csz)+1),4)),2) AS State,
RIGHT(RTRIM(csz),CHARINDEX('
',REVERSE(RTRIM(csz)))-1) AS
Zip
FROM #TestCityStateZip





GETUTCDATE
SELECT GETUTCDATE()

Returns the datetime value representing the current UTC time (Universal Time
Coordinate or Greenwich Mean Time). The current UTC time is derived from the
current local time and the time zone setting in the operating system of the
computer on which SQL Server is running.

		</summary>
	</entry>
		<entry>
		<title>
			Javascript functions
		</title>
		<link href="http://sscheral.atwiki.com/page/Javascript%20functions" />
		

		<id>@wiki::32/</id>
		<published>
			2007-09-19
			
		</published>
		<updated>
			2007-09-19T04:35:08Z
		</updated>
		
		
				
		<summary>
			
Some javascript functions...
As all of us know javascript is the mostly used
script language for web development. But we cann't say it is perfect one. Let
see some functions that will help us to avoid some javascript
problems....
typeof(a)
　　　 Though the typeof operator can be used to find the type of objects, it has
got some problems. so we can use the following global functions to wrap the
typeof operator.
isIEObject(a)
Internet Explorer holds references to objects that are not actually javascript
objects. So if we use the objects in javascript it will give error. But the
typeof operator identifies them as javascript objects( problem!!!). Here we can
use the isIEObject() function to identify those
objects.Script:function isIEObject(a)
{
　 　return isObject(a) &amp;amp;&amp;amp; typeof a.constructor != 'function';
}

isArray(a)This function returns true if a is an
array, meaning that it was produced by the Array constructor or by the [ ]
array literal notation.Script:function isArray(a)
{
　return isObject(a) &amp;amp;&amp;amp; a.constructor == Array;
}

isBoolean(a)
This function returns true if a is one of the Boolean values, true or
false.
Script:function isBoolean(a)
{
　 　return typeof a == 'boolean';
}
isEmpty(a)
This function returns true if a is an object or array or function containing no
enumerable members.Script:function isEmpty(o)
{
　 　if (isObject(o))
　{
　　　 　 for (var i in o)
　 {
　　　　　 　　return false;
　　　 　 }
　 　}
　 　return true;
}

isFunction(a)
This function returns true if a is a function. Beware that some native
functions in IE were made to look like objects instead of functions. This
function does not detect that.Netscape is better behaved in this regard.
Script:function isFunction(a)
{
　 　return typeof a == 'function';
}
isNull(a)
This function returns true if a is the null value.Script:function isNull(a)
{
　 　return typeof a == 'object' &amp;amp;&amp;amp; !a;
}
isNumber(a)This function returns true if a is
a finite number. It returns false if a is NaN or Infinite. It also returns
false if a is a string that could be converted to a number.
Script:function isNumber(a)
{
　 　return typeof a == 'number' &amp;amp;&amp;amp; isFinite(a);
}
isObject(a)
This function returns true if a is an object, array, or function. It returns
false if a is a string, number, Boolean, null, or
undefined.Script:function
isObject(a)
{
　　 return (typeof a == 'object' &amp;amp;&amp;amp; !!a) || isFunction(a);
}
isString(a)
This function returns true if a is a string.
Script:function isString(a)
{
　　 return typeof a == 'string';
}
isUndefined(a)This function returns true if a is the
undefined value. You can get the undefined value from an uninitialized variable
or from an object's missing member.
Script:function isUndefined(a)
{
　　 return typeof a == 'undefined';
}

		</summary>
	</entry>
		<entry>
		<title>
			VB.NET and C-Sharp Description
		</title>
		<link href="http://sscheral.atwiki.com/page/VB.NET%20and%20C-Sharp%20Description" />
		

		<id>@wiki::31/</id>
		<published>
			2007-09-14
			
		</published>
		<updated>
			2007-09-14T06:48:24Z
		</updated>
		
		
				
		<summary>
			
VB.NET AND C# Description
 




NotInheritable


Sealed


Specifies that a class cannot be
used as a base class, i.e. that it cannot be inherited.




NotOverridable


Sealed


Specifies that a
method cannot be overridden.




MustInherit


Abstract


Specifies that a
class can only be inherited (an instance of the class cannot be
created).




MustOverride


Abstract


Specified that a
method must be implemented in a derived class.




Overridable


Virtual


Specifies that a
member can be overridden.




Shared


Static


Specifies that a
member be shared by all instances of a class. An instance of the class is not
required to call the member.




Static


No
equivalent


Specifies that a
local variable's value be preserved between calls.




Public


Public


Class/member is visible outside of
project or assembly.




Friend


Internal


Class/member is
invisible outside of the assembly.




Private


Private


Class/member is
visible only within the project.




Overloads


not
required


Specifies that a
member is overloading another member.




Overrides


override


Specifies that a member is
overriding another member.




Implements
I1


class
C1:I1


Specifies that
the class (C1) implements the interface I1.




Inherits
C2


class
C1:C2


Specifies that
the class (C1) inherits class C2.




Implements I1
Inherits C2


class
C1:C2,I1


Specifies that
the class (C1) implements the interface I1 and inherits class C2.




Shadows


new


 




Finalize


~C1
(destructor)


Method called by
system just before garbage collection reclaims object. C1 is
classname.




New


C1


Constructor
method, called when object is created. C1 is classname.




Dim x as
Int32


Int32
x


Declares
variable x as type System.Int32.




Dim t1 As New SomeType()
Try
t1.SomeMethod()
Finally
If (t1 Is Nothing) Then
If TypeOf t1 Is IDisposable Then
CType(t1, IDisposable).Dispose()
End If
End If
End Try


using(SomeType
t1 = new SomeType())
{
t1.SomeMethod;
}


 




Imports


using


Allows methods
to be called without fully qualifying with Namespace name.




&amp;lt;&amp;gt; 


[]


Specifies
parameters.




Function x as Int32
Sub y


Int32 x
void y


Specifies return
values (Int32 and none).




_


;


Line
continuation character in VB, end of line character in C#.




AndAlso
OrElse


&amp;amp;&amp;amp;
||


Short circuit
versions of And and Or.




not
supported


&amp;lt;&amp;lt;
&amp;gt;&amp;gt;


Shift
operators.




X+=1 (x=x+1)
X-=1 (x=x-1)
also *=, /=, ^= etc..


x++
x--


Short cut
incrementers.




Dim x(4) as Int32
= 5 items (0 to 4)


Int32[] x = new
Int32[4];
= 4 items (0 to 3)


Differences in
array declarations and the number of elements created.




Dim x as
Int32


Int32 x =
0


x initialised as
zero automatically in VB.




ReDim
Preserve


no
equivalent


Redimensions an
array.




Optional


need to overload
sub instead


Specifies and
optional parameter.




Select Case
x
Case True
Case Else
End Select


switch(I)
{
case 1:break;
default:break;
};


 




ByVal
ByRef


not required
ref


Passing
parameters by value and by reference.




Me


this


Refer to the
current object.




MyBase


base


Refer to the
base calss.




MyClass


no
eqivalent


Make a
non-virtual call to a virtual method of the current object.




Const


const
readonly


Declare a
constant.




Enum


enum


Declare an
enumerator.




Structure


struct


Declare a
structure.




no
equivalent


volatile


Declare that an
object can be modifed asynchronously.




obj =
Nothing


obj ==
null


Test for an
object variable that does not point to anything.




Option
Explicit


on by default
and not changable


Specify that all
variables must be declared.




IsDBNull


no
equivalent


Test for a
database Null.




Default


must use
indexer


Specify default
method of a class.




WithEvents


no
equivalent


Declare a
variable whose events you wish to handle.




Handles


no
equivalent


Specify that the
method is an event sink.




Try
Catch
Finally
End Try


try{}
catch{}
finally{}


Structured
exception handling




If Number &amp;lt;
10 Then
Digits = 1
ElseIf Number &amp;lt; 100 Then
' Condition evaluates to True so the next statement is executed.
Digits = 2
Else
Digits = 3
End If


if (x &amp;gt;
10)
{
if (y &amp;gt; 20)
Console.Write(&quot;Statement_1&quot;);
}
else
Console.Write(&quot;Statement_2&quot;);


Conditions.




For I = 1 To
10
For J = 1 To 10
For K = 1 To 10
' Statements to operate with current values of I, J, and K.
Next K
Next J
Next I


for (int i = 1;
i &amp;lt;= 5; i++)
Console.WriteLine(i);


Iterations.




REM
'


/* ... */
//


Comment
lines




not
supported


///


XML comment
lines




Dim x As String
= &quot;Hello&quot;
Dim y As Char = GetChar(x, 1)


string x =
&quot;hello&quot;;
char y;
y = x[1];


Retrieve a
character from a String.




AddressOf


delegate


Use the address
of a method.




With ... End
With


no
equivalent


Evaluate an
object one and use many times.




Dim a() as Long
= {1,2,3}


int[] x = new
int[4] {1,2,3,4};


Initialise an
array.




Event
RaiseEvent


event


Declare and
raise an event.




SyncLock


lock


Threading
primitives.




Defaults to Private
Scope
- Variable in class
Defaults to Public
Scope
- Variable in Structure
- Structure
- Class
- Method in Class
- Method in Structure


Defaults to Private
Scope
- Variable in class
- Variable in struct
- Method in class
- Method in struct
Defaults to Public
Scope
- struct
- class


 




no
equivalent


public void ShowWord()
{
string Word;
myWord(out Word);
Console.Writeline(&quot;Word is &quot; + Word);
}
public void myWord (out string Word)
{
Word = &quot;Hello World&quot;;
}


An output parameter is a parameter
that is passed from a called method to the method that called it, that is,
the
reverse direction. Output parameters are useful if you want a method to return
more than a single value.




see
@
Visual Basic .NET
Help.ShowHelp(MyForm, &quot;C:\myHelpFile.htm&quot;)
Visual C#
Help.ShowHelp(MyForm, @&quot;C:\myHelpFile.htm&quot;);


@


 




 

		</summary>
	</entry>
		<entry>
		<title>
			Java Script Support
		</title>
		<link href="http://sscheral.atwiki.com/page/Java%20Script%20Support" />
		

		<id>@wiki::30/</id>
		<published>
			2007-09-14
			
		</published>
		<updated>
			2007-09-14T06:05:48Z
		</updated>
		
		
				
		<summary>
			
JavaScript
support
Information about what JavaScript technologies
the browsers support. Note that although XPath is used by XSLT, it is only
considered here if it can be accessed using JavaScript. External links lead to
information about support in future versions of the browsers or extensions that
provide such functionality.




Browser


JavaScript


ECMAScript
3


DOM
1


DOM
2


DOM
3


XPath


DHTML


XMLHttpRequest


Rich
editing




Amaya


No


No


No


No


No


No


No


No


No




AOL
Explorer


Yes


Yes


Partial


No


No


No


Yes


Yes


Yes




Avant


Yes


Yes


Partial


No


No


No


Yes


Yes


Yes




Camino


Yes


Yes


Yes


Yes


No †


Yes


Yes


Yes


Yes




Dillo


No


No


No


No


No


No


No


No


No




ELinks


Partial


Yes


No


No


No


No


No


No


No




Epiphany


Yes


Yes


Yes


Yes


No †


Yes


Yes


Yes


Yes




Flock


Yes


Yes


Yes


Yes


No †


Yes


Yes


Yes


Yes




Galeon


Yes


Yes


Yes


Yes


No †


Yes


Yes


Yes


Yes




iCab


Yes


Yes


Partial


Partial


No


No


Yes


Yes


No




Internet
Explorer


Yes


Yes


Partial


No †


No


Yes


Yes


Yes


Yes




Internet Explorer for
Mac


Yes


Yes


Partial


No


No


No


Yes


No


No




K-Meleon


Yes


Yes


Yes


Yes


No †


Yes


Yes


Yes


Yes




Konqueror


Yes


Yes


Yes


Yes


Partial


No


Yes


Yes


No




Links


Partial


No


No


No


No


No


No


No


No




Lynx


No


No


No


No


No


No


No


No


No




Maxthon


Yes


Yes


Partial


No


No


Yes


Yes


Yes


Yes




Mosaic


No


No


No


No


No


No


No


No


No




Mozilla


Yes


Yes


Yes


Yes


No †


Yes


Yes


Yes


Yes




Mozilla
Firefox


Yes


Yes


Yes


Yes


No †


Yes


Yes


Yes


Yes




Netscape


Yes


Yes


Yes


Yes


No †


Yes


Yes


Yes


Yes




Netscape
Browser


Yes


Yes


Depends


Depends


No †


Depends


Yes


Yes


Yes




Netscape
Navigator


Yes


Partial


No


No


No


No


Yes


No


No




OmniWeb


Yes


Yes


Yes


Yes


No


No


Yes


Yes


No




Opera


Yes


Yes


Yes


Yes


Partial


Yes


Yes


Yes


Yes




Safari


Yes


Yes


Yes


Yes


Partial †


Yes †


Yes


Yes


Yes




SeaMonkey


Yes


Yes


Yes


Yes


No †


Yes


Yes


Yes


Yes




Shiira


Yes


Yes


Yes


Yes


No


No


Yes


Yes


Yes




WorldWideWeb


No


No


No


No


No


No


No


No


No




w3m


No


No


No


No


No


No


No


No


No





		</summary>
	</entry>
	
</feed>