Showing posts with label Sql Server. Show all posts
Showing posts with label Sql Server. Show all posts

Sunday, August 2, 2009

Fetching Comma Separated Value In One Column MSSQL

In this example i am going to describe how to combine multiple records in a column in MS SQL into one record comma separated.I have used the customer table of the northwind database. What I want to do is to get the Country name in one column and then in the second column I want to have company names separated by the comma. Here is the output of the simple select statement.
And here is the out put of the desired result.


Here is the script used to produce the comma separated values. Here I have first declared the local variable which is used to save the comma separated values and I have set the length of the variable to 1000, you can change it to your desired capacity. In the next statement I have used the @EmployeeNames variable to store the Comma separated value. And I have used the Coalesce function which is used to returns the first nonnull expression among its arguments.
Declare @EmployeeNames VARCHAR(1000)
Select @EmployeeNames=Coalesce(@EmployeeNames,'') + CompanyName +';' from Customers where country='UK'
Select distinct Country,@EmployeeNames As CompanyName from Customers where Country='UK'

And at the end I have used the simple select statement to fetch the record with the same where clause which is used in assigning the @EmployeeNames variable.

All and any comments / bugs / suggestions are welcomed!


Monday, July 27, 2009

Paging In Sql Server 2000 Store Procedure

You have heard or at least done Paging of the gridview control on the server side. When someone talk about the paging of the data on the sql server side I was surprise how to do the paging of the data on sql server side on in the store procedure which will return data. Then I have start search on doing paging of data on the store procedure side.
Here is piece of code which is used to create the store procedure and the name of the store procedure is GetCustomer. The store procedure will take two parameter one the PageNumber and the second one the PageSize. At the beginning of the store procedure is the declaration of the variable which are used in the store procedure. First is the StartingRow and the EndingRow variable which are used to return the pageSize records by comparing the StartingRow and The EndingRow with the RowNumber of the return result set. Next variable is the TotalRecods which is used to save the total of the records and used to calculate the row number as I have discuss in my last Post, where I have discuss how to calculate row number in sql server 2000 in detail.
ALTER PROCEDURE [GetCustomer]
@PageNumber INT,
@PageSize INT
AS
Declare @StartingRow INT,
@EndingRow INT,
@TotalRecords INT

Declare @tblTemporary TABLE
(
RowNumber INT,
CustomerID VARCHAR(10),
CompanyName NVARCHAR(200),
ContactName NVARCHAR(200),
Country NVARCHAR(50)
)

Set @TotalRecords =(Select Count(*) from Customers)
Set @EndingRow = @PageNumber * @PageSize
Set @StartingRow = @EndingRow - @PageSize

Insert INTO @tblTemporary
Select @TotalRecords -(Select Count(*) from Customers WHERE Customer.CustomerID < CustomerID) AS RowNumber,
CustomerID,CompanyName,ContactName,Country from Customers AS Customer

Select * from @tblTemporary
Where RowNumber> @StartingRow AND RowNumber <= @EndingRow
Next is the declaration of the table to save the return record set. Here I have included the required columns which I need to display to user plus the addition column RowNumber, which is used to filter the records based on the StartingRow and EndingRow. After the declaration of the variables next is the assignment statements. In the first of the assignment statement, TotalRow is assign value by selecting the Count(*) from the customer table.Next is to calculate the EndingRow value by multipling the PageNumber with PageSize and at the last assignment statement, calculating the StartingRow by substracting the PageSize from the EndingRow variable.
In the next statement, calculating the Row Number and required columns from the customer table and inserting the returned record in the @tblTemporary table. At the end of the store procedure selecting the records from the tblTemporary table and place the where clause so that the RowNumber of the tblTemporary table will be in between the StartingRow and EndingRow.

Note: Replace the alter keyword at the start of the store procedure with the create keyword so that new store procedure will be created.

The database for this store procedure is the northwind and table is the customer table. After creating the store procedure you can run these commands to see the result

exec getCustomer 1,25
exec getCustomer 2,25


All and any comments / bugs / suggestions are welcomed!


Saturday, July 25, 2009

Spliting Comma Seperated Values in Sql server 2000

Unfortunately, there is no built-in support for arrays in SQL Server's T-SQL. SQL Server 2000 did add some new datatypes like sql_variant, bigint etc, but no support for the much needed arrays. There are some situations, that require the ability to pass a list of values to a stored procedure. Think about a web page, that lets the user select one or more of his/her previous orders, on submit, retrieves complete information about the selected orders. In this case, passing a list of selected order numbers to the stored procedure, in one go, and getting the results back is more efficient, compared to calling the same stored procedure for each selected order number.
Since, we cannot create arrays of variables or input parameters or columns in T-SQL, we need to look for workarounds and alternatives. Over the years, programmers developed different techniques, some of which are not so efficient, some efficient, but complex. The most popular technique is to pass in a list of values, separated by commas (CSV). With this method, the normal input parameter of the stored procedure receives a list of say, OrderIDs, separated by commas.
In this post I which is taken from the this link you can read this article for further reading, I will try to make a table from the CSV. I have divide code in two parts List 1 contain the declaration of the variable and List 2 contain the execution statements. And at the end full code combining the List 1 and List 2.
Here is the List 1 code which has the declaration of the variables. The @strCommSeparatedValue will contain the Comma separated value I have set the size of the of the variable to 500 and its type is NVARCHAR. Next I have declared the Int type variable named @intRowNumber which is used to assign the ID to each of the comma separated value. After the declaration of the both the variable I have set the value of the both the variables.
Declare @strCommaSeparatedValue NVARCHAR(500)
Declare @intRowNumber INT

Set @strCommaSeparatedValue ='Item 1,Item 2,Item 3,Item 4,Item 5,Item 6'
Set @intRowNumber = 1

Declare @tblTemporary Table
(
ItemID INT,
ItemName NVARCHAR(500)
)

DECLARE @strCurrentItem NVARCHAR(500),
@intFirstCommaPosition INT

SET @strCommaSeparatedValue = LTRIM(RTRIM(@strCommaSeparatedValue ))+ ','
SET @intFirstCommaPosition = CHARINDEX(',', @strCommaSeparatedValue , 1)
List 1
Next in the List 1 is the declaration of the table which has only two column the ItemID and the ItemName which are of INT and NVARCHAR type. Which is used to hold the values which are separated by comma and place in this tabel named @tblTemporary. Next I have declare the @strCurrentItem of type NVARCHAR which is used to hold the current item from the CSV. The @intFirstCommaPosition variable is used to hold the position of the first comma from the left side. Now in the next statement which is used to trim the value of the CSV from both side by using the LTRIM which is used to removing leading blanks and RTRIM which is used truncating all trailing blanks and both the LTRIM and RTRIM return the character string and at the end added the last comma in the CSV value so that to access the last item from the CSV. In the next statemetn I have assign the value to the @intFirstCommaPosistion variable by using the CHARINDEX which will returns the starting position of the specified expression in a character string.
Here is the List 2 code which is used separate the CSV value. First the if condition is place to check if there is value in the CSV and user didn't pass only the commas in the string value. In the next statement while loop is place which is used to check the value of the @intFirstCommaPosition, for greater the 0(zero). In the next statement which is use to get the first item from the CSV by using the Left function of the sql server. The left function will returns the left part of a character string with the specified number of characters.
IF REPLACE(@strCommaSeperatedValue, ',', '') <>''
BEGIN
WHILE @intFirstCommaPosition > 0
BEGIN
SET @strCurrentItem = LTRIM(RTRIM(LEFT(@strCommaSeperatedValue, @intFirstCommaPosition - 1)))
IF @strCurrentItem <> ''
BEGIN
INSERT INTO @tblTemporary (ItemID,ItemName) VALUES (@intRowNumber,@strCurrentItem)
END
SET @strCommaSeparatedValue = RIGHT(@strCommaSeperatedValue, LEN(@strCommaSeperatedValue) - @intFirstCommaPosition)
SET @intFirstCommaPosition = CHARINDEX(',', @strCommaSeparatedValue , 1)
SET @intRowNumber = @intRowNumber+1
END
END

SELECT * from @tblTemporary
List 2

After extracting the first element from the CSV , next is to check the current item for the empty string. So if condition is place to check the empty string, so that empty string can't be inserted in the @tblTemporary table. If if condition is true mean the current item is not equal to the empty string then insert it in the @tblTemporary table. Next is to assign the new string to the @strCommaSeparatedValue variable by removing the currently added item in the table. Here Right function is used which returns the right part of a character string with the specified number of characters. Here I have passed the @strCommaSeparatedValue and then then length of the @strCommaSeparatedValue minus the @intFirstCommaPosition, so that the current item is remove which is place before the first comma position. Next assign new value to the @intFirstCommaPosition variable and increment the @intRowNumber.

Note: you can place the @intRowNumber in the if condition where the current item is check for the empty string and then inserted int he @tblTemporary table.So if there is empty string then @intRowNumer is increamented only for the non-empty string values.
Declare @strCommaSeparatedValue NVARCHAR(500)
Declare @intRowNumber INT

Set @strCommaSeparatedValue ='Item 1,Item 2,Item 3,Item 4,Item 5,Item 6'
Set @intRowNumber = 1

Declare @tblTemporary Table
(
ItemID INT,
ItemName NVARCHAR(500)
)

DECLARE @strCurrentItem NVARCHAR(500),
@intFirstCommaPosition INT

SET @strCommaSeparatedValue = LTRIM(RTRIM(@strCommaSeparatedValue ))+ ','
SET @intFirstCommaPosition = CHARINDEX(',', @strCommaSeparatedValue , 1)

IF REPLACE(@strCommaSeperatedValue, ',', '') <>''
BEGIN
WHILE @intFirstCommaPosition > 0
BEGIN
SET @strCurrentItem = LTRIM(RTRIM(LEFT(@strCommaSeperatedValue, @intFirstCommaPosition - 1)))
IF @strCurrentItem <> ''
BEGIN
INSERT INTO @tblTemporary (ItemID,ItemName) VALUES (@intRowNumber,@strCurrentItem)
END
SET @strCommaSeparatedValue = RIGHT(@strCommaSeperatedValue, LEN(@strCommaSeperatedValue) - @intFirstCommaPosition)
SET @intFirstCommaPosition = CHARINDEX(',', @strCommaSeparatedValue , 1)
SET @intRowNumber = @intRowNumber+1
END
END

SELECT * from @tblTemporary
Final Code

Above is the full and the final code, you can copy past it and test it yourself. During this I have learned lot of new thing like the LTRIM, RTRIM , LEFT , RIGHT etc regarding the string manipulation.

Reference
1- Passing a list/array to an SQL Server stored procedure
2- String Functions

All and any comments / bugs / suggestions are welcomed!


Calculating Row Number in Sql Server 2000

During work in the sql server 2005 many of the new thing has been found in the sql server one of which is the ROW_NUMBER() is a new function that is added to the SQL Server 2005 T-SQL syntax. ROW_NUMBER() is used to assign ranks to the result of a query. Here is the sample output of using the Row_Number, the first column contains the serialNumber.

Here is the simple t-sql statements which are used to perform same kind of functionality as the Row_Number function in the sql server 2005.

Use NorthWind

Declare @TotalRecord INT
Set @TotalRecord=(Select Count(*) from Employees )

Select @TotalRecord-(Select Count(*) from Employees where Employee.EmployeeID < EmployeeID) as SerialNumber,
EmployeeName=FirstName+' '+LastName, Title, HireDate, Country from Employees AS Employee
In the above t-sql statement I have declare variable which is used to save the total number of records which is the @TotalRecord. And I have used it in the select statement to subtract the number of record remaining of the current record.
I have used the northwind database and in that database I have used the employees table. Hope you like this post and get some knowledge from this post.

All and any comments / bugs / suggestions are welcomed!


Sunday, April 5, 2009

How to Get All table names of a DataBase

While working in sql server and writing queries in the Query analyzer I often need to go to the Object browser window and go through the database and then find out the name of the table to which i need to write query. Then i start my search on how to find the table name by using any command in the query analyzer. And here is the solution to my problem, now i can find whole list of the table names which are in the database. which is found from this source
USE NORTHWIND
SELECT * FROM information_schema.tables
ORDER BY table_TYPE
Contains one row for each table in the current database for which the current user has permissions. The INFORMATION_SCHEMA.TABLES view is based on the sysobjects system table. To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name. And here is the second way you can use to get list of table names from database of northwind. And here is the output of the above command.


As you can see that it consist of the following columns.
Column nameData typeDescription
TABLE_CATALOGnvarchar(128)Table qualifier.
TABLE_SCHEMAnvarchar(128)Table owner.
TABLE_NAMEsysnameTable name.
TABLE_TYPEvarchar(10)Type of table. Can be VIEW or BASE TABLE.
Or you can use the sysobjects directly and get more information about the objects contained in the database. The sysobjects contains one row for each object (constraint, default, log, rule, stored procedure, and so on) created within a database. From the below select command i have set the type of the return value to 'U', which only return me the values of the tables contained in the database.
USE NORTHWIND
SELECT * FROM sysobjects
WHERE TYPE='U'
Here is the list of possible values for the type column
  • C = CHECK constraint
  • D = Default or DEFAULT constraint
  • F = FOREIGN KEY constraint
  • FN = Scalar function
  • IF = Inlined table-function
  • K = PRIMARY KEY or UNIQUE constraint
  • L = Log
  • P = Stored procedure
  • R = Rule
  • RF = Replication filter stored procedure
  • S = System table
  • TF = Table function
  • TR = Trigger
  • U = User table
  • V = View
  • X = Extended stored procedure
By removing the where clause from the above select statement you can get all the objects.Hope you will get some idea of how to get the information of the object in the database.
All and any comments / bugs / suggestions are welcomed!

Tuesday, November 4, 2008

Serial Number in Sql Server Select statement

During one of my task in daily routine i come to problem where i need addition column in the select statement of the sql server. And after the research on the net i have found a link which gave solution to my problem. Vmaceda has give the solution of how to get the serial number in select statement, both for sql server 2000 and also for sql server 2005, just for my friends i write the select statements which i have used and for there easyness.

For Sql server 2005
SELECT Column1 ,Column2 = ROW_NUMBER() OVER(ORDER BY Column1),
FROM tblTableName

For Sql Server 2000
SELECT ( SELECT SUM(1) FROM tblTableName WHERE Column1 <= tableName.Column1) AS 'Serial Number'
FROM tblTableName tableName