SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Script to split a comma seperated string to table

By Renu Mehta,

Multiple Customers were selected from a interface created in VB. A stored procedure was created which accepts the customer codes as a parameter in the form of 100,200,300,400. Wanted to fetch the information for only those customers selected. Ideally we will have to create a dynamic SQL which would be somewhat like this
Set @StrSQL =
‘Select * from Customers where CustomerCode IN (‘
+ @CustomerCode + ‘)’
I wanted to do the same without the use of dynamic SQL.
I have tried to find inbuilt procedure/function which splits a delimited string into table.
If u pass a string as '100,200,300,400' then it returns a table having 2 columns as DataValue and ValueAt. The DataValue column contains the values and the ValueAt column will contain the position of the value in the string.
Select *
from DBO.JUF_SplitStringToTable('100,200,300,400, ',')
The result for the above query would be as
DataValue ValueAt
100 1
200 2
300 3
400 4
Now my above query without Dynamic SQL would be as
Eg.: Select * from Customers where CustomerCode IN
(Select DataValue
from DBO.JUF_SplitStringToTable('100,200,300,400, ',')

Total article views: 362 | Views in the last 30 days: 1
Related Articles

Customize SQL Query



Not Selecting All Columns in select query

Not Selecting All Columns in select query


Custom calculations in Dynamic Column Groups

how to perform Custom calculations in Dynamic Column Groups


Dynamic Columns from Stored Proc Dataset

Creating a report from stored proc dataset where columns are dynamically created depending on custom...


Dynamic column selection

I have 15 columns and I want to select info on one based on a parameter pased into the proc