Friday, February 25, 2011

Execute the following script in Query Editor to generate a set of 10 random products at each execution:

select top 10 Name from Production.Product
order by newid()

Execute the following script in Query Editor to create a paging stored procedure for sales order detail:



Use AdventureWorks;
Create Proc dbo.procSalesGetPageOfData
(
@PageSize as int,
@PageNo int
)
As
Begin

With ctePaging
As
(
Select
Top(@PageSize * @PageNo) Row_number()
Over (Order by SalesOrderID, SalesOrderDetailID) as SeqNo,
OrderQty, UnitPrice, LineTotal, ModifiedDate
From Sales.SalesOrderDetail
)
Select * from ctePaging
where SeqNo > ((@PageNo - 1) * @PageSize)

End
go

-- exec dbo.procSalesGetPageOfData 10,351

Create temp table with identity instant select statement

SELECT SequentialRowNumber = identity(INT,1,1),ROW_NUMBER()
        OVER (ORDER BY CustID) AS Row,* into mytit1 from #customers

We can do the same thing in a Sql Server Query also


DECLARE @fruitNames VARCHAR(8000) 
SELECT @fruitNames = COALESCE(@fruitNames + ', ', '') + FruitName FROM Fruits
SELECT FruitNames = @fruitNames

SQL:Row Number to select Statement

SELECT ROW_NUMBER()
        OVER (ORDER BY CustID) AS Row,* from #customers

Load Comma Delimited file (csv) in SQL Server



We often need to import data that comes from different data sources, into a database like SQL Server. Usually data comes in the form of a comma delimited file aka CSV file.
Note: To handle complex scenarios and large files, use a utility like DTS/SSIS (SQL Server Integration Services). However for simpler scenarios, the approach shown in this article works fine.
These are the two easy ways to import data from a CSV file into a table of a SQL Server Database – Using Bulk Insert and Using SQL Server Management Studio.
Consider the following data
1,test,89300
2,testing,52801
3,test,1000

Create a file name test.csv in your system and add the data shown above in that file
Create a test table
CREATE TABLE test(
id int,
names varchar(100),
amount decimal(12,2)
)

Method 1: Using Bulk Insert
bulk insert csv
Here’s the same query for you to try out
bulk insert test from 'F:\test.csv'
with
(
fieldterminator=',',
rowterminator='\n'
)

The above code reads data from the file located at F:\text.csv and splits data into different
columns based on the fieldterminator ‘,’ (comma) and into different rows based on the rowterminator '\n' (\n is for newline).
Now if you do a SELECT * FROM test you will get the following output
image

Find duplicates in a table and delete them using SQL Server 2005

It is a very common requirement to find duplicates in table based on a column or set of columns and then delete them. Let us see how to do that:

Sample Table

DROP TABLE #Customers
GO

CREATE TABLE #Customers (CustID int, CustName varchar(10), PostalCode int)
INSERT #Customers SELECT 1,'A',100
INSERT #Customers SELECT 1,'B',100
INSERT #Customers SELECT 2,'C',100
INSERT #Customers SELECT 3,'D',100
INSERT #Customers SELECT 4,'E',100
INSERT #Customers SELECT 5,'F',100
INSERT #Customers SELECT 5,'G',100
INSERT #Customers SELECT 6,'H',200
INSERT #Customers SELECT 7,'I',300

Find Duplicates in CustID

SELECT CustID
FROM #Customers
GROUP BY CustID HAVING count(*) > 1

returns you the duplicate CustID

Delete Duplicates in the Customer table

SET ROWCOUNT 1
SELECT NULL
WHILE @@rowcount > 0
DELETE cust
FROM #Customers as cust
INNER JOIN
(SELECT CustID
FROM #Customers
GROUP BY CustID HAVING count(*) > 1)
AS c ON c.CustID = cust.CustID
SET ROWCOUNT 0

SELECT * FROM #Customers

Database Table schema

onsidering you want to display field names from DB , just get top(0) rows which will give u just the schema.
 below is the code for same which retrives only column names with no time.
  
 
string sqlQuery = "Select top(0) from tableName"// top(0) gives u just the schema ie. column name from table
   
  using(SqlConnection conn = new SqlConnection())
 {
 
  conn.Open();
  Using(SqlCommand cmd = new SqlCommand(sqlQuery,Conn))
  {
  SqlDatareader reader = cmd.ExecuteReader();
  DataTable dt = new DataTable();
  dt.load(reader);
   //fill the listbox with column name
  
   ForEach(DataColumn column In dt.Columns)
  {
    listbox1.Items.Add(column.ColumnName);
  }
}
}
 
 
Yes you right, right now you want all columns so just give wind card character * . change the below query as shown below

"Select top(0)* from tableName"

Thursday, February 24, 2011

Distinct datatable Rows

  Dim dttemp As New DataTable
                            dttemp = dydt1.Copy
                            dttemp.DefaultView.RowFilter = "ref = '" & dt3.Rows(i - 1)("ref").ToString & "'"
                            dttemp = dttemp.DefaultView.ToTable()


Wednesday, February 16, 2011

The Sign of a Number

In arithmetic, a number is considered as being negative (less than 0), null (equal to 0), or positive (higher than 0). When a number is negative, it must have a - symbol to its left. If it is positive, it may display a + symbol to its left or it can omit it. A number without the - or + symbol to its left is considered positive, also referred to as unsigned. The symbol that determines whether a number is positive or negative is referred to as its sign. The sign is easily verifiable if you know the number already. In some cases, when a number is submitted to your application, before taking any action, you may need to get this piece of information.
To find out if a value is positive, null, or negative, Transact-SQL provides the SIGN() function. Its syntax is:
SIGN(Expression)
This function takes as argument a number or an expression that can be evaluated to a number. The interpreter would then examine the number:
  • If the Expression is positive, the function returns 1. Here is an example:
     
    DECLARE @Number As int;
    SET @Number = 24.75;
    SELECT SIGN(@Number) AS [Sign of 1058];
    GO
  • If the Expression is null, the function returns 0
     
    DECLARE @Number As int;
    SET @Number = 0;
    SELECT SIGN(@Number) AS [Sign of Number];
    GO
  • If the Expression is negative, the function returns -1
     
    DECLARE @Number As int;
    SET @Number = -57.05;
    SELECT SIGN(@Number) AS [Sign of -57.05];
    GO
Based on this, you can use the SIGN() function to find out whether a value is negative, null, or positive: simply pass the value (or a variable) to SIGN() and use a logical operator to check its sign.

Monday, February 14, 2011

Create filter in datatable

Dim dttemp As New DataTable
                            dttemp = dydt1.Copy
                            dttemp.DefaultView.RowFilter = "Student = '" & dydt1.Rows(i - 1)("Student").ToString & "'"
                            dttemp = dttemp.DefaultView.ToTable()

Script manager error sys undefined...

You must add these lines in the web.config

<httpHandlers>
  <remove verb="*" path="*.asmx"/>
  <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>

Sunday, February 13, 2011

Parameter out sample

alter proc Proc_Grade    
(     
@class Varchar(100),     
@Mark numeric(15, 2)  ,   
@ret varchar(100) out   
)     
As     
Begin   
DECLARE @OUTPUT varchar(100)
Set @ret=[dbo].Grade (@class ,@Mark)
print @ret
End


 Public Function Geetgrade(ByVal classs As String, ByVal ADDNEW As Double) As String
        Dim result As String
        con.Close()
        con.Open()
        cmd.Parameters.Clear()
        cmd = con.CreateCommand
        cmd.CommandText = "Proc_Grade"
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@class", classs)
        cmd.Parameters.AddWithValue("@Mark", ADDNEW)
        cmd.Parameters.Add("@ret", SqlDbType.VarChar, 100).Direction = ParameterDirection.Output
        cmd.ExecuteNonQuery()
        result = cmd.Parameters("@ret").Value
        con.Close()
        Return result
    End Function

Datatable Distinct Colm


dim dt as datatable
Dim dtTemp As DataTable
dt=dtTemp.DefaultView.ToTable(true,"Roomtype") 

Sunday, February 6, 2011

DATABASE BACKUP UP AND RESTORE

RESTORE DB
 
CREATE proc RestoreSRBDB 

 
@filePath nvarchar(400) 

as 
Begin 
--IF db_id('SRBDB') IS NOT NULL 
--DROP DATABASE SRBDB 
--ELSE 
--Print 'Database Does Not Exists' 
--create database SRBDB 
RESTORE DATABASE SRBDB FROM  DISK = @filePath WITH  FILE = 1,  REPLACE, 
STATS = 10 
End

BACKUP DB

CREATE proc BackupSRBDB 

@filePath nvarchar(400) 

as 
Begin 
 
BACKUP DATABASE  SRBDB 
 TO  DISK =@filePath 
 
End 

Database Exist or not

Create Database
Public Function CreateInstanceDb(ByVal DBName As String) As Boolean
        Dim strSQL As String = "CREATE DATABASE  [" & DBName & "]"
        If ExecuteScript(strSQL) Then
            Return True
        Else
            Return False
        End If
    End Function
Check Database Exist
 Public Function CheckDB(ByVal DBName As String)
        Dim ret_val As String
        conn = Nothing
        conn = New SqlConnection(SQL_CONNECTION_STRING)
        dt = New DataTable
        da = New SqlDataAdapter("SELECT [name] FROM Master..sysdatabases WHERE [name] = N'" & DBName & "'", conn)
        da.Fill(dt)
        If dt.Rows.Count > 0 Then
            ret_val = "S"
        Else
            ret_val = "N"
        End If
        Return ret_val
    End Function

Saturday, February 5, 2011

Session

I have had success with assigning the session variable in a script block on the page markup, then using that variable in the external JavaScript source file.  Semi-psuedocode from the page and JS source follows, respectively:

In page markup:
...
<body ...>
    
<script type='text/javascript'>
        var sessionVarForJS = "<%= sessionVariable %>";
    
</script>
    
<script type='text/javascript' src='./js/externalJS.js'></script>
...

In externalJS.js:
...
    if (sessionVarForJS == "somethingDesired")
        doSomething(
"whatever");
...

Example::

You cannot in anyway get the session values in an external .js file. If you need to get the session values into javascript, the javascript has to be on the same page or you can declare a javascript variable that gets set with the session value on the aspx page and then use this variable in the external .js file. However you will need to first declare the variable and then write the code for including the external js file like this

<script language='javascript'>
var sessionVar = <%=Session("ABC")%>
</script>
<script type="text/javascript" src="./ext.js"></script>
 
///
 
Then inside ext.js you can use the variable sessionVar




Add an icon to your page's address bar


Shows the method that should be used to display an icon for your website in your browser's address bar
Place this code inside the <head></head> section of your page
  1.    
  2. <link rel="shortcut icon" href="logo.ico" type="image/x-icon" />  
  

Table of Contents

Objective

Objective of this article is to put all mostly used function related in SQL Server 2005. There are several function that we are used regularly in SQL Server 2005. This article is will a common place for all those function with proper example.
But, I need your help. This Table of Contents and Article is editable by all Silver members and above. What I want you to do is replace the entries in the Table of Contents below add as many as function you aware on SQL Server 2005 or above. This will really help beginners to find out all of them under a single article.
I am starting with few function related to DateTime function. I will update the article regular manner, but I expect a major contribution from you guys. Please don't forget to update the History list with your name and code project profile link.
Thanks in advance for supporting my one small initiative.

DateTime Function in SQL Server

Below are the most commonly used DateTime function in SQL Server.
  • GETDATE()
  • DATEADD()
  • DATEPART()
  • DATEDIFF()
  • DATENAME()
  • DAY()
  • MONTH()
  • YEAR()

GETDATE()

GETDATE() is very common used method which returns exact date time from the system. It does not accept any parameter. Just call it like simple function.
Example :
 Collapse
Declare @Date datetime 
set @Date = (SELECT GETDATE());
Print @Date 
OutPut:
 Collapse
Aug 15 2009  9:04PM 

DATEADD()

DATEADD() is used to add or subtract datetime. Its return a new datetime based on the added or subtracted interval.
General Syntax
 Collapse
DATEADD(datepart, number, date)
datepart is the parameter that specifies on which part of the date to return a new value. Number parameter is used to increment datepart.
Example :
 Collapse
Declare @Date datetime 
set @Date = (SELECT GETDATE());
print  @Date -- Print Current Date
-- Adding 5 days with Current Date
SELECT DATEADD(day, 5,@Date ) AS NewTime
Output :
 Collapse
Aug 15 2009  9:19PM
NewTime
-----------------------
2009-08-20 21:19:15.170

DATEPART()

DATEPART() is used when we need a part of date or time from a datetime variable. We can use DATEPART() method only with select command.
Syntax
 Collapse
DATEPART(datepart, date)
Example :
 Collapse
-- Get Only Year
SELECT DATEPART(year, GETDATE()) AS 'Year'
-- Get Only Month
SELECT DATEPART(month, GETDATE()) AS 'Month'
-- Get Only hour
SELECT DATEPART(hour, GETDATE()) AS 'Hour
Output :
 Collapse
Year
-----------
2009
Month
-----------
8
Hour
-----------
21

DATEDIFF()

DATEDIFF() is very common function to find out the difference between two DateTime elements.
Syntax
 Collapse
DATEDIFF(datepart, startdate, enddate)
Example :
 Collapse
-- Declare Two DateTime Variable
Declare @Date1 datetime 
Declare @Date2 datetime 
-- Set @Date1 with Current Date
set @Date1 = (SELECT GETDATE());
-- Set @Date2 with 5 days more than @Date1
set @Date2 = (SELECT DATEADD(day, 5,@Date1 ))
-- Get The Date Difference
SELECT DATEDIFF(day, @Date1, @Date2) AS DifferenceOfDay
Output :
 Collapse
DifferenceOfDay
---------------
5 

DATENAME()

DATENAME() is very common and most useful function to find out the date name from the datetime value.
Example
 Collapse
-- Get Today 
SELECT DATENAME(dw, getdate()) AS 'Today Is'
-- Get Mont name
SELECT DATENAME(month, getdate()) AS 'Month'
Output :
 Collapse
Today Is
------------------------------
Saturday
Month
------------------------------
August

DAY()

DAY() is used to get the day from any date time object.
Example:
 Collapse
SELECT DAY(getdate()) AS 'DAY'
Output :
 Collapse
DAY
-----------
15

MONTH()

 Collapse
SELECT MONTH(getdate()) AS 'Month'
Output :
 Collapse
Month
-----------
8

YEAR()

 Collapse
SELECT YEAR(getdate()) AS 'Year'
Output :
 Collapse
Year
-----------
2009

String Functions

Some of the String Functions comes very handy at times. Let us discuss them one by one.

ASCII()

Returns the ASCII code value of the leftmost character of a character expression.

Syntax
 Collapse
ASCII ( character_expression ) 
Arguments: character_expression : Is an expression of the type char or varchar.
Return Types: Int 
Example 
 Collapse
SELECT ASCII('A')  

SET TEXTSIZE 0
SET NOCOUNT ON
-- Create the variables for the current character string position 
-- and for the character string.
DECLARE @position int, @string char(15)
-- Initialize the variables.
SET @position = 1
SET @string = 'The codeProject'
WHILE @position <= DATALENGTH(@string)
   BEGIN
   SELECT ASCII(SUBSTRING(@string, @position, 1)),
      CHAR(ASCII(SUBSTRING(@string, @position, 1)))
    SET @position = @position + 1
   END
SET NOCOUNT OFF
Output:
 Collapse
-----------
65
----------- ----
84          T
----------- ----
104         h
----------- ----
101         e
----------- ----
and so on..... 

CHAR()  

Converts an int ASCII code to a character.  
Syntax
 Collapse
CHAR ( integer_expression ) 
Arguments: integer_expression: Is an integer from 0 through 255. NULL is returned if the integer expression is not in this range.
Return Types:  character  
Example 
 Collapse
SET TEXTSIZE 0
SET NOCOUNT ON
DECLARE @intCounter int
SET @intCounter = 0

WHILE (@intCounter<= 255)
 BEGIN
  SELECT 'CHAR - ' + CHAR(@intCounter) + '. ASCII - ' + CONVERT(VARCHAR,@intCounter) 
  SET @intCounter = @intCounter + 1
 END


SET NOCOUNT OFF
Output:
 Collapse
CHAR - !. ASCII - 33
------------------------------------------------
CHAR - ". ASCII - 34
------------------------------------------------
CHAR - #. ASCII - 35
------------------------------------------------
CHAR - $. ASCII - 36
------------------------------------------------
CHAR - %. ASCII - 37
------------------------------------------------
CHAR - &. ASCII - 38
------------------------------------------------
CHAR - '. ASCII - 39
------------------------------------------------
CHAR - (. ASCII - 40
------------------------------------------------

and so on.....  

NCHAR() 

Return a unicode character representing a number passed as a parameter.
Syntax 
 Collapse
NCHAR ( integer_expression )  
Return Types:  character 
Example : 
 Collapse
SELECT NCHAR(97) 
OutPut
 Collapse
This will return the leter "a"

DIFFERENCE()

Returns an integer value that indicates the difference between the SOUNDEX values of two character expressions.
Syntax
 Collapse
DIFFERENCE ( character_expression , character_expression )
Arguments:character_expression: Is an expression of type char or varchar. character_expression can also be of type text; however, only the first 8,000 bytes are significant.
Return Types:  Int
Example :
 Collapse
USE AdventureWorks;
GO
-- Returns a DIFFERENCE value of 4, the least possible difference.
SELECT SOUNDEX('Green'), SOUNDEX('Greene'), DIFFERENCE('Green','Greene');
GO
-- Returns a DIFFERENCE value of 0, the highest possible difference.
SELECT SOUNDEX('Blotchet-Halls'), SOUNDEX('Greene'), DIFFERENCE('Blotchet-Halls', 'Greene');
GO
Output:
 Collapse
----- ----- ----------- 
G650  G650  4           

(1 row(s) affected)
                        
----- ----- ----------- 
B432  G650  0           

(1 row(s) affected)

LEFT() 

Returns the left most characters of a string.
Syntax
 Collapse
LEFT(string, length) 
string 
Specifies the string from which to obtain the left-most characters.

length 
Specifies the number of characters to obtain.
Example :
 Collapse
SELECT LEFT('Marufuzzaman',5)  
OutPut
 Collapse
Maruf

RIGHT()

Returns the right most characters of a string.
Syntax  
 Collapse
RIGHT(string, length) 
string 
Specifies the string from which to obtain the left-most characters.

length 
Specifies the number of characters to obtain.
Example :
 Collapse
SELECT RIGHT('Md. Marufuzzaman',12)  
OutPut 
 Collapse
Marufuzzaman 

LTRIM() 

Returns a character expression after it removes leading blanks.
Example :
 Collapse
SELECT LTRIM('   Md. Marufuzzaman') 
OutPut 
 Collapse
Md. Marufuzzaman

RTRIM()

Returns a character string after truncating all trailing blanks. 
Example : 
 Collapse
SELECT RTRIM('Md. Marufuzzaman    ') 
OutPut 
 Collapse
Md. Marufuzzaman

REPLACE() 

Returns a string with all the instances of a substring replaced by another substring.
Syntax
 Collapse
REPLACE(find, replace, string)
Find 
Specifies the string that contains the substring to replace all instances of with another.

Replace 
Specifies the substring to locate.

String 
Specifies the substring with which to replace the located substring.

Example :
 Collapse
SELECT REPLACE('The codeProject is ?.','?', 'your development resource')
OutPut:
 Collapse
The codeProject is your development resource.

QUOTNAME()

Returns a Unicode string with the delimiters added to make the input string a valid Microsoft SQL Server delimited identifier.
Syntax
 Collapse
QUOTENAME ( 'character_string' [ , 'quote_character' ] )  
Arguments
' character_string '
Is a string of Unicode character data. character_string is sysname and is limited to 128 characters. Inputs greater than 128 characters return NULL.

' quote_character '
Is a one-character string to use as the delimiter. Can be a single quotation mark ( ' ), a left or right bracket ( [ ] ), or a double quotation mark ( " ). If quote_character is not specified, brackets are used.

Return Typesnvarchar(258) 

Examples : 
The following example takes the character string abc[]def and uses the [ and ] characters to create a valid SQL Server delimited identifier.

 Collapse
SELECT QUOTENAME('abc[]def')
OutPut:
 Collapse
[abc[]]def] 

REVERSE()

Returns a character expression in reverse order. 
Example :
 Collapse
SELECT REVERSE('namazzufuraM .dM')
Output: 
 Collapse
Md. Marufuzzaman 

CHARINDEX

CharIndex returns the first occurance of a string or characters within another string. The Format of CharIndex is given Below:
CHARINDEX expression1 , expression2 [ , start_location )
Here expression1 is the string of characters to be found within expression2. So if you want to search ij within the word Abhijit, we will use ij as expression1 and Abhijit as expression2start_location is an optional integer argument which identifies the position from where the string will be searched. Now let us look into some examples :
 Collapse
SELECT CHARINDEX('SQL', 'Microsoft SQL Server') 
OUTPUT:
 Collapse
11

So it will start from 1 and go on searching until it finds the total string element searched, and returns its first position. The Result will be 0 if the searched string is not found.

We can also mention the Start_Location of the string to be searched.

EXAMPLE:
 Collapse
SELECT CHARINDEX('SQL', 'Microsoft SQL server has a great SQL Engine',12)
So in the above example we can have the Output as 34 as we specified the StartLocation as 12, which is greater than initial SQL position(11).

PATINDEX

As a contrast PatIndex is used to search a pattern within an expression. The Difference between CharIndex and PatIndex is the later allows WildCard Characters.
PATINDEX '%pattern%' , expression)
Here the first argument takes a pattern with wildcard characters like '%' (meaning any string) or '_' (meaning any character).

For Example
PATINDEX('%BC%','ABCD')

Output:  
 Collapse
2

Another flexibility of PATINDEX is that you can specify a number of characters allowed within the Pattern. Say you want to find all of the records that contain the words "Bread", or "bread" in a string, You can use the following :
 Collapse
SELECT PATINDEX('%[b,B]read%', 'Tommy loves Bread') 
In this example, we mentioned both b and B in square brackets. The Result will be 13 which is same if we have searched in 'Tommy loves bread'.

LEN

Len is a function which returns the length of a string. This is the most common and simplest function that everyone use. Len Function excludes trailing blank spaces.
 Collapse
SELECT LEN('ABHISHEK IS WRITING THIS')
This will output 24, it is same when we write LEN('ABHISHEK IS WRITING THIS ') as LEN doesnt take trailing spaces in count.

STUFF


Stuff is another TSql Function which is used to delete a specified length of characters within a string and replace with another set of characters. The general syntax of STUFF is as below :

STUFF(character_expression1, start, length, character_expression2)Character_Expression1 represents the string in which the stuff is to be applied. start indicates the starting position of the character in character_expression1length is the length of characters which need to be replaced. character_expression2 is the string that will be replaced to the start position.

Let us take an example :
 Collapse
SELECT STUFF('SQL SERVER is USEFUL',5,6,'DATABASE')

So the result will be :
SQL DATABASE is USEFUL

SUBSTRING


Substring returns the part of the string from a given characterexpression. The general syntax of Substring is as follows :

SUBSTRING(expression, start, length)
Here the function gets the string from start to length. Let us take an example below:
 Collapse
SELECT OUT = SUBSTRING('abcdefgh', 2, 3)
The output will be "bcd".
Note : substring also works on ntext, VARCHAR, CHAR etc.

LOWER / UPPER


Anoter simple but handy function is Lower / UPPER. The will just change case of a string expression. For Example,
 Collapse
SELECT UPPER('this is Lower TEXT') 

Output:
THIS IS LOWER TEXT