Split string by two delimiters into two columns - sql

I have a string value which has numeric values separated by comma and then by a pipe. I want to split them into a table with two columns. I could split the string by one delimiter but unfortunately couldn't find a way to split by two. Please help.
DECLARE #list NVARCHAR(MAX) = '1,101|2,202|3,303';
The result should be like below.
1 101
2 202
3 303
Thanks in advance.

If you're using SQL Server 2016 or Azure, you have access to the new SPLIT_STRING function. If not I recommend using Jeff Moden's DelimitedSplit8K function, which is widely regarded as the fastest, most efficient SQL based string splitter available...
DECLARE #list NVARCHAR(MAX) = '1,101|2,202|3,303';
SELECT
Col1 = LEFT(dsk.Item, sl.SplitLocation - 1),
Col2 = SUBSTRING(dsk.Item, sl.SplitLocation + 1, LEN(dsk.Item))
FROM
dbo.DelimitedSplit8K(#list, '|') dsk -- code for DelimitedSplit8K can be found here... http://www.sqlservercentral.com/articles/Tally+Table/72993/
CROSS APPLY ( VALUES (ISNULL(NULLIF(CHARINDEX(',', dsk.Item, 1), 0), 1)) ) sl (SplitLocation);

CREATE FUNCTION [dbo].[fn_Split_char](#text nvarchar(max), #delimiter varchar(20) = ' ')
RETURNS #Strings TABLE
(
position int IDENTITY PRIMARY KEY,
value nvarchar(max)
)
AS
BEGIN
DECLARE #index int
SET #index = -1
WHILE (LEN(#text) > 0)
BEGIN
SET #index = CHARINDEX(#delimiter , #text)
IF (#index = 0) AND (LEN(#text) > 0)
BEGIN
INSERT INTO #Strings VALUES (#text)
BREAK
END
IF (#index > 1)
BEGIN
INSERT INTO #Strings VALUES (LEFT(#text, #index - 1))
SET #text = RIGHT(#text, (LEN(#text) - #index))
END
ELSE
SET #text = RIGHT(#text, (LEN(#text) - #index))
END
RETURN
END
Select LEFT(value, Charindex(',', value) - 1) ,
RIGHT(value, Charindex(',', Reverse(value)) - 1) ,
* from [fn_Split_char] ('1,101|2,202|3,303', '|')

Use xml path and cross apply to create multiple rows for a single row based on the pipe separator and then use substring w.r.t the commas to derive two desired columns
Create table #temp(list nvarchar(max))
Insert into #temp values('1,101|2,202|3,303')
SELECT
Substring(Tbl.Col.value('./text()[1]','varchar(50)'),1,1)as col1,
Substring(Tbl.Col.value('./text()[1]','varchar(50)'),charindex(',',Tbl.Col.value('./text()[1]','varchar(50)'),1)+1,len(Tbl.Col.value('./text()[1]','varchar(50)')))
FROM
(Select cast('<a>'+ replace((SELECT list As [*] FOR XML PATH ('')), '|', '</a><a>') + '</a>' as xml)as t
from #temp) tl
Cross apply
tl.t.nodes('/a') AS Tbl(Col)

Try using this Table-valued Function, embed this SP to your main SP
ALTER FUNCTION [dbo].[delimiter]
(
#PARAM_IDS AS VARCHAR(MAX)
#PARAM_DELIMITER AS CHAR(1)
)
RETURNS
#NEW_TABLE TABLE
(
NUM INT NOT NULL IDENTITY,
ID INT NOT NULL
)
AS
BEGIN
DECLARE #NEXTSTRING AS NVARCHAR(MAX);
DECLARE #POS AS INT;
DECLARE #STRING AS NVARCHAR(MAX);
DECLARE #DELIMITER AS NVARCHAR(MAX);
SET #STRING = #PARAM_IDS;
SET #DELIMITER = #PARAM_DELIMITER;
SET #STRING = #STRING + #DELIMITER;
SET #POS = CHARINDEX(#DELIMITER,#STRING);
WHILE (#POS <> 0)
BEGIN
SET #NEXTSTRING = SUBSTRING(#STRING,1,#POS - 1);
INSERT #NEW_TABLE (ID) VALUES (#NEXTSTRING);
SET #STRING = SUBSTRING(#STRING,#POS+1,len(#STRING));
SET #POS = CHARINDEX(#DELIMITER,#STRING);
END
RETURN
END
then example of use
SET #DETAILS_COUNT = (SELECT COUNT(*) FROM delimiter(#PARAM_MS_UNIT_ID, #DELIMITER));

Related

Query stuff result left join on multiple ids [duplicate]

Duplicate of
Dynamic SQL Comma Delimited Value Query
Parameterized Queries with Like and In
I have a SQL Server Stored Procedure where I would like to pass a varchar full of comma delimited values to an IN function. For example:
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE tableid IN (#Ids);
This does not work of course. I get the error:
Conversion failed when converting the varchar value '1,2,3,5,4,6,7,98,234' to data type int.
How can I accomplish this (or something relatively similar) without resorting to building dynamic SQL?
Of course if you're lazy like me, you could just do this:
Declare #Ids varchar(50) Set #Ids = ',1,2,3,5,4,6,7,98,234,'
Select * from sometable
where Charindex(','+cast(tableid as varchar(8000))+',', #Ids) > 0
Don't use a function that loops to split a string!, my function below will split a string very fast, with no looping!
Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:
CREATE TABLE Numbers
(Number int NOT NULL,
CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE #x int
SET #x=0
WHILE #x<8000
BEGIN
SET #x=#x+1
INSERT INTO Numbers VALUES (#x)
END
use this function to split your string, which does not loop and is very fast:
CREATE FUNCTION [dbo].[FN_ListToTable]
(
#SplitOn char(1) --REQUIRED, the character to split the #List string on
,#List varchar(8000) --REQUIRED, the list to split apart
)
RETURNS
#ParsedList table
(
ListValue varchar(500)
)
AS
BEGIN
/**
Takes the given #List string and splits it apart based on the given #SplitOn character.
A table is returned, one row per split item, with a column name "ListValue".
This function workes for fixed or variable lenght items.
Empty and null items will not be included in the results set.
Returns a table, one row per item in the list, with a column name "ListValue"
EXAMPLE:
----------
SELECT * FROM dbo.FN_ListToTable(',','1,12,123,1234,54321,6,A,*,|||,,,,B')
returns:
ListValue
-----------
1
12
123
1234
54321
6
A
*
|||
B
(10 row(s) affected)
**/
----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
INSERT INTO #ParsedList
(ListValue)
SELECT
ListValue
FROM (SELECT
LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(#SplitOn, List2, number+1)-number - 1))) AS ListValue
FROM (
SELECT #SplitOn + #List + #SplitOn AS List2
) AS dt
INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
WHERE SUBSTRING(List2, number, 1) = #SplitOn
) dt2
WHERE ListValue IS NOT NULL AND ListValue!=''
RETURN
END --Function FN_ListToTable
you can use this function as a table in a join:
SELECT
Col1, COl2, Col3...
FROM YourTable
INNER JOIN FN_ListToTable(',',#YourString) s ON YourTable.ID = s.ListValue
Here is your example:
Select * from sometable where tableid in(SELECT ListValue FROM dbo.FN_ListToTable(',',#Ids) s)
No Table No Function No Loop
Building on the idea of parsing your list into a table our DBA suggested using XML.
Declare #Ids varchar(50)
Set #Ids = ‘1,2,3,5,4,6,7,98,234’
DECLARE #XML XML
SET #XML = CAST('<i>' + REPLACE(#Ids, ',', '</i><i>') + '</i>' AS XML)
SELECT *
FROM
SomeTable
INNER JOIN #XML.nodes('i') x(i)
ON SomeTable .Id = x.i.value('.', 'VARCHAR(MAX)')
These seems to have the same performance as #KM's answer but, I think, a lot simpler.
You can create a function that returns a table.
so your statement would be something like
select * from someable
join Splitfunction(#ids) as splits on sometable.id = splits.id
Here is a simular function.
CREATE FUNCTION [dbo].[FUNC_SplitOrderIDs]
(
#OrderList varchar(500)
)
RETURNS
#ParsedList table
(
OrderID int
)
AS
BEGIN
DECLARE #OrderID varchar(10), #Pos int
SET #OrderList = LTRIM(RTRIM(#OrderList))+ ','
SET #Pos = CHARINDEX(',', #OrderList, 1)
IF REPLACE(#OrderList, ',', '') <> ''
BEGIN
WHILE #Pos > 0
BEGIN
SET #OrderID = LTRIM(RTRIM(LEFT(#OrderList, #Pos - 1)))
IF #OrderID <> ''
BEGIN
INSERT INTO #ParsedList (OrderID)
VALUES (CAST(#OrderID AS int)) --Use Appropriate conversion
END
SET #OrderList = RIGHT(#OrderList, LEN(#OrderList) - #Pos)
SET #Pos = CHARINDEX(',', #OrderList, 1)
END
END
RETURN
END
It's a very common question. Canned answer, several nice techniques:
http://www.sommarskog.se/arrays-in-sql-2005.html
This works perfectly! The below answers are too complicated. Don't look at this as dynamic. Set up your store procedure as follows:
(#id as varchar(50))
as
Declare #query as nvarchar(max)
set #query ='
select * from table
where id in('+#id+')'
EXECUTE sp_executesql #query
I can suggest using WITH like this:
DECLARE #Delim char(1) = ',';
SET #Ids = #Ids + #Delim;
WITH CTE(i, ls, id) AS (
SELECT 1, CHARINDEX(#Delim, #Ids, 1), SUBSTRING(#Ids, 1, CHARINDEX(#Delim, #Ids, 1) - 1)
UNION ALL
SELECT i + 1, CHARINDEX(#Delim, #Ids, ls + 1), SUBSTRING(#Ids, ls + 1, CHARINDEX(#Delim, #Ids, ls + 1) - CHARINDEX(#Delim, #Ids, ls) - 1)
FROM CTE
WHERE CHARINDEX(#Delim, #Ids, ls + 1) > 1
)
SELECT t.*
FROM yourTable t
INNER JOIN
CTE c
ON t.id = c.id;
I think a very simple solution could be following:
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE ','+#Ids+',' LIKE '%,'+CONVERT(VARCHAR(50),tableid)+',%';
Without using dynamic SQL, you have to take the input variable and use a split function to put the data into a temp table and then join to that.
Thanks, for your function I Used IT........................
This is my EXAMPLE
**UPDATE [RD].[PurchaseOrderHeader]
SET [DispatchCycleNumber] ='10'
WHERE OrderNumber in(select * FROM XA.fn_SplitOrderIDs(#InvoiceNumberList))**
CREATE FUNCTION [XA].[fn_SplitOrderIDs]
(
#OrderList varchar(500)
)
RETURNS
#ParsedList table
(
OrderID int
)
AS
BEGIN
DECLARE #OrderID varchar(10), #Pos int
SET #OrderList = LTRIM(RTRIM(#OrderList))+ ','
SET #Pos = CHARINDEX(',', #OrderList, 1)
IF REPLACE(#OrderList, ',', '') <> ''
BEGIN
WHILE #Pos > 0
BEGIN
SET #OrderID = LTRIM(RTRIM(LEFT(#OrderList, #Pos - 1)))
IF #OrderID <> ''
BEGIN
INSERT INTO #ParsedList (OrderID)
VALUES (CAST(#OrderID AS int)) --Use Appropriate conversion
END
SET #OrderList = RIGHT(#OrderList, LEN(#OrderList) - #Pos)
SET #Pos = CHARINDEX(',', #OrderList, 1)
END
END
RETURN
END
If you use SQL Server 2008 or higher, use table valued parameters; for example:
CREATE PROCEDURE [dbo].[GetAccounts](#accountIds nvarchar)
AS
BEGIN
SELECT *
FROM accountsTable
WHERE accountId IN (select * from #accountIds)
END
CREATE TYPE intListTableType AS TABLE (n int NOT NULL)
DECLARE #tvp intListTableType
-- inserts each id to one row in the tvp table
INSERT #tvp(n) VALUES (16509),(16685),(46173),(42925),(46167),(5511)
EXEC GetAccounts #tvp
Its been a while but I have done this in the past using XML as a interim.
I can't take any credit for this, but I'm afraid I no longer know where I got this idea from:
-- declare the variables needed
DECLARE #xml as xml,#str as varchar(100),#delimiter as varchar(10)
-- The string you want to split
SET #str='A,B,C,D,E,Bert,Ernie,1,2,3,4,5'
-- What you want to split on. Can be a single character or a string
SET #delimiter =','
-- Convert it to an XML document
SET #xml = cast(('<X>'+replace(#str,#delimiter ,'</X><X>')+'</X>') as xml)
-- Select back from the XML
SELECT N.value('.', 'varchar(10)') as value FROM #xml.nodes('X') as T(N)
Create a table function like below which parse comma separated varchar and returns a table that can be inner joined with other tables.
CREATE FUNCTION [dbo].[fn_SplitList]
(
#inString varchar(MAX) = '',
#inDelimiter char(1) = ',' -- Keep the delimiter to 100 chars or less. Generally a delimiter will be 1-2 chars only.
)
RETURNS #tbl_Return table
(
Unit varchar(1000) COLLATE Latin1_General_BIN
)
AS
BEGIN
INSERT INTO #tbl_Return
SELECT DISTINCT
LTRIM(RTRIM(piece.value('./text()[1]', 'varchar(1000)'))) COLLATE DATABASE_DEFAULT AS Unit
FROM
(
--
-- Replace any delimiters in the string with the "X" tag.
--
SELECT
CAST(('<X>' + REPLACE(s0.prsString, s0.prsSplitDelimit, '</X><X>') + '</X>') AS xml).query('.') AS units
FROM
(
--
-- Convert the string and delimiter into XML.
--
SELECT
(SELECT #inString FOR XML PATH('')) AS prsString,
(SELECT #inDelimiter FOR XML PATH('')) AS prsSplitDelimit
) AS s0
) AS s1
CROSS APPLY units.nodes('X') x(piece)
RETURN
END
=================================================
Now consume above created table function in your code,creation of function is one time activity in your database that can be used across databases as well on same server.
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT
*
FROM sometable AS st
INNER JOIN fn_SplitList(#ids, ',') AS sl
ON sl.unit = st.tableid
I've written a stored procedure to show how to do this before.
You basically have to process the string.
I tried to post the code here but the formatting got all screwy.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[uspSplitTextList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[uspSplitTextList]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
-- uspSplitTextList
--
-- Description:
-- splits a separated list of text items and returns the text items
--
-- Arguments:
-- #list_text - list of text items
-- #Delimiter - delimiter
--
-- Notes:
-- 02/22/2006 - WSR : use DATALENGTH instead of LEN throughout because LEN doesn't count trailing blanks
--
-- History:
-- 02/22/2006 - WSR : revised algorithm to account for items crossing 8000 character boundary
-- 09/18/2006 - WSR : added to this project
--
CREATE PROCEDURE uspSplitTextList
#list_text text,
#Delimiter varchar(3)
AS
SET NOCOUNT ON
DECLARE #InputLen integer -- input text length
DECLARE #TextPos integer -- current position within input text
DECLARE #Chunk varchar(8000) -- chunk within input text
DECLARE #ChunkPos integer -- current position within chunk
DECLARE #DelimPos integer -- position of delimiter
DECLARE #ChunkLen integer -- chunk length
DECLARE #DelimLen integer -- delimiter length
DECLARE #ItemBegPos integer -- item starting position in text
DECLARE #ItemOrder integer -- item order in list
DECLARE #DelimChar varchar(1) -- first character of delimiter (simple delimiter)
-- create table to hold list items
-- actually their positions because we may want to scrub this list eliminating bad entries before substring is applied
CREATE TABLE #list_items ( item_order integer, item_begpos integer, item_endpos integer )
-- process list
IF #list_text IS NOT NULL
BEGIN
-- initialize
SET #InputLen = DATALENGTH(#list_text)
SET #TextPos = 1
SET #DelimChar = SUBSTRING(#Delimiter, 1, 1)
SET #DelimLen = DATALENGTH(#Delimiter)
SET #ItemBegPos = 1
SET #ItemOrder = 1
SET #ChunkLen = 1
-- cycle through input processing chunks
WHILE #TextPos <= #InputLen AND #ChunkLen <> 0
BEGIN
-- get current chunk
SET #Chunk = SUBSTRING(#list_text, #TextPos, 8000)
-- setup initial variable values
SET #ChunkPos = 1
SET #ChunkLen = DATALENGTH(#Chunk)
SET #DelimPos = CHARINDEX(#DelimChar, #Chunk, #ChunkPos)
-- loop over the chunk, until the last delimiter
WHILE #ChunkPos <= #ChunkLen AND #DelimPos <> 0
BEGIN
-- see if this is a full delimiter
IF SUBSTRING(#list_text, (#TextPos + #DelimPos - 1), #DelimLen) = #Delimiter
BEGIN
-- insert position
INSERT INTO #list_items (item_order, item_begpos, item_endpos)
VALUES (#ItemOrder, #ItemBegPos, (#TextPos + #DelimPos - 1) - 1)
-- adjust positions
SET #ItemOrder = #ItemOrder + 1
SET #ItemBegPos = (#TextPos + #DelimPos - 1) + #DelimLen
SET #ChunkPos = #DelimPos + #DelimLen
END
ELSE
BEGIN
-- adjust positions
SET #ChunkPos = #DelimPos + 1
END
-- find next delimiter
SET #DelimPos = CHARINDEX(#DelimChar, #Chunk, #ChunkPos)
END
-- adjust positions
SET #TextPos = #TextPos + #ChunkLen
END
-- handle last item
IF #ItemBegPos <= #InputLen
BEGIN
-- insert position
INSERT INTO #list_items (item_order, item_begpos, item_endpos)
VALUES (#ItemOrder, #ItemBegPos, #InputLen)
END
-- delete the bad items
DELETE FROM #list_items
WHERE item_endpos < item_begpos
-- return list items
SELECT SUBSTRING(#list_text, item_begpos, (item_endpos - item_begpos + 1)) AS item_text, item_order, item_begpos, item_endpos
FROM #list_items
ORDER BY item_order
END
DROP TABLE #list_items
RETURN
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
I have same idea with user KM. but do not need extra table Number. Just this function only.
CREATE FUNCTION [dbo].[FN_ListToTable]
(
#SplitOn char(1) --REQUIRED, the character to split the #List string on
,#List varchar(8000) --REQUIRED, the list to split apart
)
RETURNS
#ParsedList table
(
ListValue varchar(500)
)
AS
BEGIN
DECLARE #number int = 0
DECLARE #childString varchar(502) = ''
DECLARE #lengthChildString int = 0
DECLARE #processString varchar(502) = #SplitOn + #List + #SplitOn
WHILE #number < LEN(#processString)
BEGIN
SET #number = #number + 1
SET #lengthChildString = CHARINDEX(#SplitOn, #processString, #number + 1) - #number - 1
IF #lengthChildString > 0
BEGIN
SET #childString = LTRIM(RTRIM(SUBSTRING(#processString, #number + 1, #lengthChildString)))
IF #childString IS NOT NULL AND #childString != ''
BEGIN
INSERT INTO #ParsedList(ListValue) VALUES (#childString)
SET #number = #number + #lengthChildString - 1
END
END
END
RETURN
END
And here is the test:
SELECT ListValue FROM dbo.FN_ListToTable('/','a/////bb/c')
Result:
ListValue
______________________
a
bb
c
-- select * from dbo.Split_ID('77,106')
ALTER FUNCTION dbo.Split_ID(#String varchar(8000))
returns #temptable TABLE (ID varchar(8000))
as
begin
declare #idx int
declare #slice varchar(8000)
declare #Delimiter char(1)
set #Delimiter =','
select #idx = 1
if len(#String)<1 or #String is null return
while #idx!= 0
begin
set #idx = charindex(#Delimiter,#String)
if #idx!=0
set #slice = left(#String,#idx - 1)
else
set #slice = #String
if(len(#slice)>0)
insert into #temptable(ID) values(#slice)
set #String = right(#String,len(#String) - #idx)
if len(#String) = 0 break
end
return
end
You could do it like this:
create or replace
PROCEDURE UDP_SETBOOKMARK
(
P_USERID IN VARCHAR2
, P_BOOKMARK IN VARCHAR2
) AS
BEGIN
UPDATE T_ER_Bewertung
SET LESEZEICHEN = P_BOOKMARK
WHERE STAMM_ID in( select regexp_substr(P_USERID,'[^,]+', 1, level) from dual
connect by regexp_substr(P_USERID, '[^,]+', 1, level) is not null )
and ER_ID = (select max(ER_ID) from T_ER_Bewertung_Kopie);
commit;
END UDP_SETBOOKMARK;
Then try it with
Begin
UDP_SETBOOKMARK ('1,2,3,4,5', 'Test');
End;
You can use this IN-Clause with regexp_substr in other situations too, just try it.
Error 493: The column 'i' that was returned from the nodes() method cannot be
used directly. It can only be used with one of the four XML data type
methods, exist(), nodes(), query(), and value(), or in IS NULL and IS NOT
NULL checks.
The above errorr was fixed in SQL Server 2014 by using following snippet
Declare #Ids varchar(50)
Set #Ids = '1,2,3,5,4,6,7,98,234'
DECLARE #XML XML
SET #XML = CAST('<i>' + REPLACE(#Ids, ',', '</i><i>') + '</i>' AS XML)
SELECT SomeTable.*
FROM
SomeTable
cross apply #XML.nodes('i') x(i)
where SomeTable .Id = x.i.value('.', 'VARCHAR(MAX)')
Try this:
SELECT ProductId, Name, Tags
FROM Product
WHERE '1,2,3,' LIKE '%' + CAST(ProductId AS VARCHAR(20)) + ',%';
As said on the last example of this link
Tons of answers here, but to add my two cents I think STRING_SPLIT is a very simple approach to this sort of problem:
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE tableid IN;
(SELECT value FROM STRING_SPLIT(#Ids, ','))
Best and simple approach.
DECLARE #AccumulateKeywordCopy NVARCHAR(2000),#IDDupCopy NVARCHAR(50);
SET #AccumulateKeywordCopy ='';
SET #IDDupCopy ='';
SET #IDDup = (SELECT CONVERT(VARCHAR(MAX), <columnName>) FROM <tableName> WHERE <clause>)
SET #AccumulateKeywordCopy = ','+#AccumulateKeyword+',';
SET #IDDupCopy = ','+#IDDup +',';
SET #IDDupCheck = CHARINDEX(#IDDupCopy,#AccumulateKeywordCopy)
CREATE TABLE t
(
id INT,
col1 VARCHAR(50)
)
INSERT INTO t
VALUES (1,
'param1')
INSERT INTO t
VALUES (2,
'param2')
INSERT INTO t
VALUES (3,
'param3')
INSERT INTO t
VALUES (4,
'param4')
INSERT INTO t
VALUES (5,
'param5')
DECLARE #params VARCHAR(100)
SET #params = ',param1,param2,param3,'
SELECT *
FROM t
WHERE Charindex(',' + Cast(col1 AS VARCHAR(8000)) + ',', #params) > 0
working fiddle find here Fiddle
I ran into the same issue, and I don't want to have any footprint on the source database - i.e. no stored procedures or functions. I went about it this way:
declare #IDs table (Value int)
insert into #IDs values(1)
insert into #IDs values(2)
insert into #IDs values(3)
insert into #IDs values(5)
insert into #IDs values(4)
insert into #IDs values(6)
insert into #IDs values(7)
insert into #IDs values(98)
insert into #IDs values(234)
SELECT *
FROM sometable
WHERE tableid IN (select Value from #IDs)
The answer by #RBarryYoung (above) worked for me.
But when you have spaces in between the comma separated string values, then it will omit IDs with spaces. So I removed the spaces.
Take a look at the code snippet below.
Declare #Ids varchar(50) Set #Ids = '1 , 2,3'
set #Ids=','+Replace(#Ids,' ', '')+',';
Select * from [tblEmployee]
where Charindex(','+cast(ID as varchar(8000))+',', #Ids) > 0
WHERE someId IN (SELECT convert(int, value) FROM string_split(#stringOfCommaDelimitedIds, ','))
The simplest way i found was to use FIND_IN_SET
FIND_IN_SET(column_name, values)
values=(1,2,3)
SELECT name WHERE FIND_IN_SET(id, values)
This came in handy for one of my requirements where I did not want to use CTE and also did not want to go with the inner join.
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT
cn1,cn2,cn3
FROM tableName
WHERE columnName in (select Value from fn_SplitString(#ids, ','))
Function for split string :
CREATE FUNCTION [dbo].[fn_SplitString] ( #stringToSplit VARCHAR(MAX), #seperator Char )
RETURNS
#returnList TABLE ([Value] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(#seperator, #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(#seperator, #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END

Reverse only numerical parts of string in sql server

With T-SQL, I'm trying to find the easiest way to reverse numbers in string. so for string like Test123Hello have Test321Hello.
[Before] [After]
Test123Hello Test321Hello
Tt143 Hello Tt341 Hello
12Hll 21Hll
Tt123H3451end Tt321H1543end
you can use this function
CREATE FUNCTION [dbo].[fn_ReverseDigit_MA]
(
#Str_IN nVARCHAR(max)
)
RETURNS NVARCHAR(max)
AS
BEGIN
DECLARE #lenstr AS INT =LEN(#Str_IN)
DECLARE #lastdigend AS INT=0
while (#lastdigend<#lenstr)
BEGIN
DECLARE #strPart1 AS NVARCHAR(MAX)=LEFT(#Str_IN,#lastdigend)
declare #lenstrPart1 AS INT=LEN(#strPart1)
DECLARE #strPart2 AS NVARCHAR(MAX)=RIGHT(#Str_IN,#lenstr-#lastdigend)
declare #digidx as int=patindex(N'%[0-9]%' ,#strPart2)+#lenstrPart1
IF(#digidx=#lenstrPart1)
BEGIN
BREAK;
END
DECLARE #strStartdig AS NVARCHAR(MAX) = RIGHT(#Str_IN,#lenstr-#digidx+1)
declare #NDidx as int=patindex(N'%[^0-9]%' ,#strStartdig)+#digidx-1
IF(#NDidx<=#digidx)
BEGIN
SET #NDidx=#lenstr+1
END
DECLARE #strRet AS NVARCHAR(MAX)=LEFT(#Str_IN,#digidx-1) +REVERSE(SUBSTRING(#Str_IN,#digidx,#NDidx-#digidx)) +RIGHT(#Str_IN,#lenstr-#NDidx+1)
SET #Str_IN=#strRet
SET #lastdigend=#NDidx-1
END
return #Str_IN
END
Just make use of PATINDEX for searching, append to the result string part by part:
CREATE FUNCTION [dbo].[fn_ReverseDigits]
(
#Value nvarchar(max)
)
RETURNS NVARCHAR(max)
AS
BEGIN
IF #Value IS NULL
RETURN NULL
DECLARE
#TextIndex int = PATINDEX('%[^0-9]%', #Value),
#NumIndex int = PATINDEX('%[0-9]%', #Value),
#ResultValue nvarchar(max) = ''
WHILE LEN(#ResultValue) < LEN(#Value)
BEGIN
-- Set the index to end of the string if the index is 0
SELECT #TextIndex = CASE WHEN #TextIndex = 0 THEN LEN(#Value) + 1 ELSE LEN(#ResultValue) + #TextIndex END
SELECT #NumIndex = CASE WHEN #NumIndex = 0 THEN LEN(#Value) + 1 ELSE LEN(#ResultValue) + #NumIndex END
IF #NumIndex < #TextIndex
SELECT #ResultValue = #ResultValue + REVERSE(SUBSTRING(#Value, #NumIndex, #TextIndex -#NumIndex))
ELSE
SELECT #ResultValue = #ResultValue + (SUBSTRING(#Value, #TextIndex, #NumIndex - #TextIndex))
-- Update index variables
SELECT
#TextIndex = PATINDEX('%[^0-9]%', SUBSTRING(#Value, LEN(#ResultValue) + 1, LEN(#Value) - LEN(#ResultValue))),
#NumIndex = PATINDEX('%[0-9]%', SUBSTRING(#Value, LEN(#ResultValue) + 1, LEN(#Value) - LEN(#ResultValue)))
END
RETURN #ResultValue
END
Test SQL
declare #Values table (Value varchar(20))
INSERT #Values VALUES
('Test123Hello'),
('Tt143 Hello'),
('12Hll'),
('Tt123H3451end'),
(''),
(NULL)
SELECT Value, dbo.fn_ReverseDigits(Value) ReversedValue FROM #Values
Result
Value ReversedValue
-------------------- --------------------
Test123Hello Test321Hello
Tt143 Hello Tt341 Hello
12Hll 21Hll
Tt123H3451end Tt321H1543end
NULL NULL
hope this help:
declare #s nvarchar(128) ='Test321Hello'
declare #numStart as int, #numEnd as int
select #numStart =patindex('%[0-9]%',#s)
select #numEnd=len(#s)-patindex('%[0-9]%',REVERSE(#s))
select
SUBSTRING(#s,0,#numstart)+
reverse(SUBSTRING(#s,#numstart,#numend-#numstart+2))+
SUBSTRING(#s,#numend+2,len(#s)-#numend)
Use this function it will handle multiple occurrence of numbers too
create FUNCTION [dbo].[GetReverseNumberFromString] (#String VARCHAR(2000))
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE #Count INT
DECLARE #IntNumbers VARCHAR(1000)
declare #returnstring varchar(max)=#String;
SET #Count = 0
SET #IntNumbers = ''
WHILE #Count <= LEN(#String)
BEGIN
IF SUBSTRING(#String, #Count, 1) >= '0'
AND SUBSTRING(#String, #Count, 1) <= '9'
BEGIN
SET #IntNumbers = #IntNumbers + SUBSTRING(#String, #Count, 1)
END
IF (
SUBSTRING(#String, #Count + 1, 1) < '0'
OR SUBSTRING(#String, #Count + 1, 1) > '9'
)
AND SUBSTRING(#String, #Count, 1) >= '0'
AND SUBSTRING(#String, #Count, 1) <= '9'
BEGIN
SET #IntNumbers = #IntNumbers + ','
END
SET #Count = #Count + 1
END
declare #RevStrings table (itemz varchar(50))
INSERT INTO #RevStrings(itemz)
select items from dbo.Split(#IntNumbers,',')
select #returnstring = Replace(#returnstring, itemz,REVERSE(itemz))from #RevStrings
RETURN #returnstring
END
your sample string
select [dbo].[GetReverseNumberFromString]('Tt123H3451end')
result
Tt321H1543end
UPDATE :
if you do not have Split function then first create it
i have included it below
create FUNCTION Split
(
#Input NVARCHAR(MAX),
#Character CHAR(1)
)
RETURNS #Output TABLE (
Items NVARCHAR(1000)
)
AS
BEGIN
DECLARE #StartIndex INT, #EndIndex INT
SET #StartIndex = 1
IF SUBSTRING(#Input, LEN(#Input) - 1, LEN(#Input)) <> #Character
BEGIN
SET #Input = #Input + #Character
END
WHILE CHARINDEX(#Character, #Input) > 0
BEGIN
SET #EndIndex = CHARINDEX(#Character, #Input)
INSERT INTO #Output(Items)
SELECT SUBSTRING(#Input, #StartIndex, #EndIndex - 1)
SET #Input = SUBSTRING(#Input, #EndIndex + 1, LEN(#Input))
END
RETURN
END
GO
This is a set based approach:
;WITH Tally (n) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)
), UnpivotCTE AS (
SELECT id, x.c, n, y.isNumber,
n - ROW_NUMBER() OVER (PARTITION BY id, y.isNumber
ORDER BY n) AS grp
FROM mytable
CROSS JOIN Tally
CROSS APPLY (SELECT SUBSTRING(col, n, 1)) AS x(c)
CROSS APPLY (SELECT ISNUMERIC(x.c)) AS y(isNumber)
WHERE n <= LEN(col)
), ToConcatCTE AS (
SELECT id, c, n, isNumber,
grp + MIN(n) OVER (PARTITION BY id, isNumber, grp) AS grpAsc
FROM UnpivotCTE
)
SELECT id, col,
REPLACE(
(SELECT c AS [text()]
FROM ToConcatCTE AS t
WHERE t.id = m.id
ORDER BY id,
grpAsc,
CASE WHEN isNumber = 0 THEN n END,
CASE WHEN isNumber = 1 THEN n END DESC
FOR XML PATH('')), ' ',' ') AS col2
FROM mytable AS m
A tally table is used in order to 'unpivot' all characters of the string. Then ROW_NUMBER is used in order to identify islands of numeric and non-numeric characters. Finally, FOR XML PATH is used to reconstruct the initial string with numerical islands reversed: ORDER BY is used to sort islands of numeric characters in reversed order.
Fiddle Demo here
This would do the specific string you are asking for:
select
substring('Test123Hello',1,4)
+
reverse(substring('Test123Hello',5,3))
+
substring('Test123Hello',8,5)
Judging by the rest of the values it looks like you would need to make templates for any of the alphanumeric patterns you are getting. For example you would apply the above to any values that had the shape:
select * from [B&A] where [before] like '[a-z][a-z][a-z][a-z][0-9][0-9][0-9]
[a-z][a-z][a-z][a-z][a-z]'
In other words, if you put the values (before and after) into a table [B&A] and called the columns 'before' and 'after' then ran this:
select
substring(before,1,4)
+
reverse(substring(before,5,3))
+
substring(before,8,5) as [after]
from [B&A] where [before] like '[a-z][a-z][a-z][a-z][0-9][0-9][0-9][a-z]
[a-z][a-z][a-z][a-z]'
Then it would give you 'Test321Hello'.
However the other 3 rows would not be affected unless you created a similar
'[0-9][a-z]' type template for each alphanumeric shape and applied this to the [B&A] table. You would have to select the results into a temp table or another table.
By applying each template in turn you'd get most of it then you'd have to see how many rows were unaffected and check what the alphanumeric shape is and make more templates. Eventually you have a set of code which, if you ran it would capture all possible combinations.
You could just sit down and design a code in this way which captured all possible combinations of [a-z] and [0-9]. A lot depends on the maximum number of characters you are dealing with.

User Defined Function to get longest word in a string in SQL Server

I've trying to create a UDF in SQL to return the longest word in a string. I've created the following but I cant get it to work properly. Any suggestions?
CREATE FUNCTION [dbo].[ufn_Longestword] (#input varchar(255))
RETURNS varchar(100)
AS
BEGIN
declare #pos int
declare #pos2 int
declare #wordpos int
declare #longestword varchar(100)
declare #Letter1 varchar (1)
declare #Letter2 varchar (1)
declare #twords table (
words varchar(100))
SET #pos = 1
WHILE #pos <= len(#input)
BEGIN
SET #Letter1 = substring(#input, #pos, 1)
IF #Letter1 = ' '
BEGIN
SET #pos2 = #pos
WHILE #pos2 <= len(#input)
BEGIN
SET #Letter2 = substring(#input, #pos2, 1)
if #letter2 = ' '
BEGIN
insert into #twords
select SUBSTRING(#input, #pos,#pos2 - #pos)
END
SET #pos2 = #pos2 + 1
END
END
SET #pos = #pos + 1
END
SET #longestword = (select top 1 words from #twords
ORDER BY len(words)desc)
delete from #twords
RETURN #longestword
END
I#m trying to get the different between the 2 spaces and insert that word into a temp table but it doesnt work.
Instead you can use this.
DECLARE #str VARCHAR(5000)='aaaa bbbbb cccccccc'
SELECT TOP 1 Split.a.value('.', 'VARCHAR(100)') as longest_Word
FROM (SELECT Cast ('<M>' + Replace(#str, ' ', '</M><M>') + '</M>' AS XML) AS Data) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)
ORDER BY Len(Split.a.value('.', 'VARCHAR(100)')) DESC
Result : cccccccc
i found this as solution :
click Here
CREATE FUNCTION FN_ex06(#str varchar(8000) )
RETURNS #T TABLE
( position int IDENTITY PRIMARY KEY,
value varchar(8000) ,
length smallint null
)
AS
BEGIN
DECLARE #i int
SET #i = -1
WHILE (LEN(#str) > 0)
BEGIN
SET #i = CHARINDEX(' ' , #str) /* here i used space as delimiter*/
IF (#i = 0) AND (LEN(#str) > 0)
BEGIN
INSERT INTO #T (value, length) VALUES (#str, LEN(#str))
BREAK
END
IF (#i > 1)
BEGIN
INSERT INTO #T (value, length) VALUES (LEFT(#str, #i - 1),
LEN(LEFT(#str, #i - 1)))
SET #str = RIGHT(#str, (LEN(#str) - #i))
END
ELSE
SET #str = RIGHT(#str, (LEN(#str) - #i))
END
RETURN
END
to run this function you treat it as table because return is a table
select max(value) from FN_ex06('karim pentester')
result is : pentester
of course you select all other columns in return table

Select * from table where column = (any value from a comma delimited string)

The user selects various words from a drop down list and these values get added into a comma delimited string. When passing the string to a stored procedure I want it to select * from a table where that word exists.
Table
id----word
1-----cat
2-----dog
3-----mouse
4-----dog
string that is passed into the stored procedure is cat, dog so returning columns 1, 2 and 4.
Is there a way of doing this in sql server?
Use IN:
SELECT *
FROM your_table
WHERE word IN ('cat', 'dog')
you first need to make a function SplitCSV :
CREATE FUNCTION [dbo].[SplitCSV] (#CSVString VARCHAR(8000), #Delimiter CHAR(1))
RETURNS #temptable TABLE (items VARCHAR(8000))
AS
BEGIN
DECLARE #pos INT;
DECLARE #slice VARCHAR(8000);
SELECT #pos = 1;
IF LEN(#CSVString) < 1 OR #CSVString IS NULL RETURN;
WHILE #pos!= 0
BEGIN
SET #pos = CHARINDEX(#Delimiter,#CSVString);
IF #pos != 0
SET #slice = LEFT(#CSVString, #pos - 1);
ELSE
SET #slice = #CSVString;
IF( LEN(#slice) > 0)
INSERT INTO #temptable(Items) VALUES (#slice);
SET #CSVString = RIGHT(#CSVString, LEN(#CSVString) - #pos);
IF LEN(#CSVString) = 0 BREAK;
END
RETURN
END
GO
then you can use it like :
SELECT *
FROM myTable
WHERE ID IN (
SELECT items FROM [dbo].[SplitCSV]('1,2,3,4,5', ',')
)
SELECT *
FROM Table
WHERE '%,' + Word + ',%' LIKE ',' + #your_csv_param + ','
Extra commas at the begin and end of parameter and column are to prevent search to match cat with catfish for example.
If you want select all animal except mouse , you can use NOT IN
SELECT * FROM
TABLE
WHERE Word Not IN('Mouse')
So you can avoid type many type of animal
CREATE FUNCTION
ALTER FUNCTION [dbo].[fn_Split](#text varchar(8000), #delimiter varchar(20) = ' ')
RETURNS #Strings TABLE
(
position int IDENTITY PRIMARY KEY,
value varchar(8000)
)
AS
BEGIN
DECLARE #index int
SET #index = -1
WHILE (LEN(#text) > 0)
BEGIN
SET #index = CHARINDEX(#delimiter , #text)
IF (#index = 0) AND (LEN(#text) > 0)
BEGIN
INSERT INTO #Strings VALUES (#text)
BREAK
END
IF (#index > 1)
BEGIN
INSERT INTO #Strings VALUES (LEFT(#text, #index - 1))
SET #text = RIGHT(#text, (LEN(#text) - #index))
END
ELSE
SET #text = RIGHT(#text, (LEN(#text) - #index))
END
RETURN
END
----
select * from yourtable where column in ( select value from fn_Split(#para1,',')

Passing a varchar full of comma delimited values to a SQL Server IN function

Duplicate of
Dynamic SQL Comma Delimited Value Query
Parameterized Queries with Like and In
I have a SQL Server Stored Procedure where I would like to pass a varchar full of comma delimited values to an IN function. For example:
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE tableid IN (#Ids);
This does not work of course. I get the error:
Conversion failed when converting the varchar value '1,2,3,5,4,6,7,98,234' to data type int.
How can I accomplish this (or something relatively similar) without resorting to building dynamic SQL?
Of course if you're lazy like me, you could just do this:
Declare #Ids varchar(50) Set #Ids = ',1,2,3,5,4,6,7,98,234,'
Select * from sometable
where Charindex(','+cast(tableid as varchar(8000))+',', #Ids) > 0
Don't use a function that loops to split a string!, my function below will split a string very fast, with no looping!
Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:
CREATE TABLE Numbers
(Number int NOT NULL,
CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE #x int
SET #x=0
WHILE #x<8000
BEGIN
SET #x=#x+1
INSERT INTO Numbers VALUES (#x)
END
use this function to split your string, which does not loop and is very fast:
CREATE FUNCTION [dbo].[FN_ListToTable]
(
#SplitOn char(1) --REQUIRED, the character to split the #List string on
,#List varchar(8000) --REQUIRED, the list to split apart
)
RETURNS
#ParsedList table
(
ListValue varchar(500)
)
AS
BEGIN
/**
Takes the given #List string and splits it apart based on the given #SplitOn character.
A table is returned, one row per split item, with a column name "ListValue".
This function workes for fixed or variable lenght items.
Empty and null items will not be included in the results set.
Returns a table, one row per item in the list, with a column name "ListValue"
EXAMPLE:
----------
SELECT * FROM dbo.FN_ListToTable(',','1,12,123,1234,54321,6,A,*,|||,,,,B')
returns:
ListValue
-----------
1
12
123
1234
54321
6
A
*
|||
B
(10 row(s) affected)
**/
----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
INSERT INTO #ParsedList
(ListValue)
SELECT
ListValue
FROM (SELECT
LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(#SplitOn, List2, number+1)-number - 1))) AS ListValue
FROM (
SELECT #SplitOn + #List + #SplitOn AS List2
) AS dt
INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
WHERE SUBSTRING(List2, number, 1) = #SplitOn
) dt2
WHERE ListValue IS NOT NULL AND ListValue!=''
RETURN
END --Function FN_ListToTable
you can use this function as a table in a join:
SELECT
Col1, COl2, Col3...
FROM YourTable
INNER JOIN FN_ListToTable(',',#YourString) s ON YourTable.ID = s.ListValue
Here is your example:
Select * from sometable where tableid in(SELECT ListValue FROM dbo.FN_ListToTable(',',#Ids) s)
No Table No Function No Loop
Building on the idea of parsing your list into a table our DBA suggested using XML.
Declare #Ids varchar(50)
Set #Ids = ‘1,2,3,5,4,6,7,98,234’
DECLARE #XML XML
SET #XML = CAST('<i>' + REPLACE(#Ids, ',', '</i><i>') + '</i>' AS XML)
SELECT *
FROM
SomeTable
INNER JOIN #XML.nodes('i') x(i)
ON SomeTable .Id = x.i.value('.', 'VARCHAR(MAX)')
These seems to have the same performance as #KM's answer but, I think, a lot simpler.
You can create a function that returns a table.
so your statement would be something like
select * from someable
join Splitfunction(#ids) as splits on sometable.id = splits.id
Here is a simular function.
CREATE FUNCTION [dbo].[FUNC_SplitOrderIDs]
(
#OrderList varchar(500)
)
RETURNS
#ParsedList table
(
OrderID int
)
AS
BEGIN
DECLARE #OrderID varchar(10), #Pos int
SET #OrderList = LTRIM(RTRIM(#OrderList))+ ','
SET #Pos = CHARINDEX(',', #OrderList, 1)
IF REPLACE(#OrderList, ',', '') <> ''
BEGIN
WHILE #Pos > 0
BEGIN
SET #OrderID = LTRIM(RTRIM(LEFT(#OrderList, #Pos - 1)))
IF #OrderID <> ''
BEGIN
INSERT INTO #ParsedList (OrderID)
VALUES (CAST(#OrderID AS int)) --Use Appropriate conversion
END
SET #OrderList = RIGHT(#OrderList, LEN(#OrderList) - #Pos)
SET #Pos = CHARINDEX(',', #OrderList, 1)
END
END
RETURN
END
It's a very common question. Canned answer, several nice techniques:
http://www.sommarskog.se/arrays-in-sql-2005.html
This works perfectly! The below answers are too complicated. Don't look at this as dynamic. Set up your store procedure as follows:
(#id as varchar(50))
as
Declare #query as nvarchar(max)
set #query ='
select * from table
where id in('+#id+')'
EXECUTE sp_executesql #query
I can suggest using WITH like this:
DECLARE #Delim char(1) = ',';
SET #Ids = #Ids + #Delim;
WITH CTE(i, ls, id) AS (
SELECT 1, CHARINDEX(#Delim, #Ids, 1), SUBSTRING(#Ids, 1, CHARINDEX(#Delim, #Ids, 1) - 1)
UNION ALL
SELECT i + 1, CHARINDEX(#Delim, #Ids, ls + 1), SUBSTRING(#Ids, ls + 1, CHARINDEX(#Delim, #Ids, ls + 1) - CHARINDEX(#Delim, #Ids, ls) - 1)
FROM CTE
WHERE CHARINDEX(#Delim, #Ids, ls + 1) > 1
)
SELECT t.*
FROM yourTable t
INNER JOIN
CTE c
ON t.id = c.id;
I think a very simple solution could be following:
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE ','+#Ids+',' LIKE '%,'+CONVERT(VARCHAR(50),tableid)+',%';
Without using dynamic SQL, you have to take the input variable and use a split function to put the data into a temp table and then join to that.
Thanks, for your function I Used IT........................
This is my EXAMPLE
**UPDATE [RD].[PurchaseOrderHeader]
SET [DispatchCycleNumber] ='10'
WHERE OrderNumber in(select * FROM XA.fn_SplitOrderIDs(#InvoiceNumberList))**
CREATE FUNCTION [XA].[fn_SplitOrderIDs]
(
#OrderList varchar(500)
)
RETURNS
#ParsedList table
(
OrderID int
)
AS
BEGIN
DECLARE #OrderID varchar(10), #Pos int
SET #OrderList = LTRIM(RTRIM(#OrderList))+ ','
SET #Pos = CHARINDEX(',', #OrderList, 1)
IF REPLACE(#OrderList, ',', '') <> ''
BEGIN
WHILE #Pos > 0
BEGIN
SET #OrderID = LTRIM(RTRIM(LEFT(#OrderList, #Pos - 1)))
IF #OrderID <> ''
BEGIN
INSERT INTO #ParsedList (OrderID)
VALUES (CAST(#OrderID AS int)) --Use Appropriate conversion
END
SET #OrderList = RIGHT(#OrderList, LEN(#OrderList) - #Pos)
SET #Pos = CHARINDEX(',', #OrderList, 1)
END
END
RETURN
END
If you use SQL Server 2008 or higher, use table valued parameters; for example:
CREATE PROCEDURE [dbo].[GetAccounts](#accountIds nvarchar)
AS
BEGIN
SELECT *
FROM accountsTable
WHERE accountId IN (select * from #accountIds)
END
CREATE TYPE intListTableType AS TABLE (n int NOT NULL)
DECLARE #tvp intListTableType
-- inserts each id to one row in the tvp table
INSERT #tvp(n) VALUES (16509),(16685),(46173),(42925),(46167),(5511)
EXEC GetAccounts #tvp
Its been a while but I have done this in the past using XML as a interim.
I can't take any credit for this, but I'm afraid I no longer know where I got this idea from:
-- declare the variables needed
DECLARE #xml as xml,#str as varchar(100),#delimiter as varchar(10)
-- The string you want to split
SET #str='A,B,C,D,E,Bert,Ernie,1,2,3,4,5'
-- What you want to split on. Can be a single character or a string
SET #delimiter =','
-- Convert it to an XML document
SET #xml = cast(('<X>'+replace(#str,#delimiter ,'</X><X>')+'</X>') as xml)
-- Select back from the XML
SELECT N.value('.', 'varchar(10)') as value FROM #xml.nodes('X') as T(N)
Create a table function like below which parse comma separated varchar and returns a table that can be inner joined with other tables.
CREATE FUNCTION [dbo].[fn_SplitList]
(
#inString varchar(MAX) = '',
#inDelimiter char(1) = ',' -- Keep the delimiter to 100 chars or less. Generally a delimiter will be 1-2 chars only.
)
RETURNS #tbl_Return table
(
Unit varchar(1000) COLLATE Latin1_General_BIN
)
AS
BEGIN
INSERT INTO #tbl_Return
SELECT DISTINCT
LTRIM(RTRIM(piece.value('./text()[1]', 'varchar(1000)'))) COLLATE DATABASE_DEFAULT AS Unit
FROM
(
--
-- Replace any delimiters in the string with the "X" tag.
--
SELECT
CAST(('<X>' + REPLACE(s0.prsString, s0.prsSplitDelimit, '</X><X>') + '</X>') AS xml).query('.') AS units
FROM
(
--
-- Convert the string and delimiter into XML.
--
SELECT
(SELECT #inString FOR XML PATH('')) AS prsString,
(SELECT #inDelimiter FOR XML PATH('')) AS prsSplitDelimit
) AS s0
) AS s1
CROSS APPLY units.nodes('X') x(piece)
RETURN
END
=================================================
Now consume above created table function in your code,creation of function is one time activity in your database that can be used across databases as well on same server.
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT
*
FROM sometable AS st
INNER JOIN fn_SplitList(#ids, ',') AS sl
ON sl.unit = st.tableid
I've written a stored procedure to show how to do this before.
You basically have to process the string.
I tried to post the code here but the formatting got all screwy.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[uspSplitTextList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[uspSplitTextList]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
-- uspSplitTextList
--
-- Description:
-- splits a separated list of text items and returns the text items
--
-- Arguments:
-- #list_text - list of text items
-- #Delimiter - delimiter
--
-- Notes:
-- 02/22/2006 - WSR : use DATALENGTH instead of LEN throughout because LEN doesn't count trailing blanks
--
-- History:
-- 02/22/2006 - WSR : revised algorithm to account for items crossing 8000 character boundary
-- 09/18/2006 - WSR : added to this project
--
CREATE PROCEDURE uspSplitTextList
#list_text text,
#Delimiter varchar(3)
AS
SET NOCOUNT ON
DECLARE #InputLen integer -- input text length
DECLARE #TextPos integer -- current position within input text
DECLARE #Chunk varchar(8000) -- chunk within input text
DECLARE #ChunkPos integer -- current position within chunk
DECLARE #DelimPos integer -- position of delimiter
DECLARE #ChunkLen integer -- chunk length
DECLARE #DelimLen integer -- delimiter length
DECLARE #ItemBegPos integer -- item starting position in text
DECLARE #ItemOrder integer -- item order in list
DECLARE #DelimChar varchar(1) -- first character of delimiter (simple delimiter)
-- create table to hold list items
-- actually their positions because we may want to scrub this list eliminating bad entries before substring is applied
CREATE TABLE #list_items ( item_order integer, item_begpos integer, item_endpos integer )
-- process list
IF #list_text IS NOT NULL
BEGIN
-- initialize
SET #InputLen = DATALENGTH(#list_text)
SET #TextPos = 1
SET #DelimChar = SUBSTRING(#Delimiter, 1, 1)
SET #DelimLen = DATALENGTH(#Delimiter)
SET #ItemBegPos = 1
SET #ItemOrder = 1
SET #ChunkLen = 1
-- cycle through input processing chunks
WHILE #TextPos <= #InputLen AND #ChunkLen <> 0
BEGIN
-- get current chunk
SET #Chunk = SUBSTRING(#list_text, #TextPos, 8000)
-- setup initial variable values
SET #ChunkPos = 1
SET #ChunkLen = DATALENGTH(#Chunk)
SET #DelimPos = CHARINDEX(#DelimChar, #Chunk, #ChunkPos)
-- loop over the chunk, until the last delimiter
WHILE #ChunkPos <= #ChunkLen AND #DelimPos <> 0
BEGIN
-- see if this is a full delimiter
IF SUBSTRING(#list_text, (#TextPos + #DelimPos - 1), #DelimLen) = #Delimiter
BEGIN
-- insert position
INSERT INTO #list_items (item_order, item_begpos, item_endpos)
VALUES (#ItemOrder, #ItemBegPos, (#TextPos + #DelimPos - 1) - 1)
-- adjust positions
SET #ItemOrder = #ItemOrder + 1
SET #ItemBegPos = (#TextPos + #DelimPos - 1) + #DelimLen
SET #ChunkPos = #DelimPos + #DelimLen
END
ELSE
BEGIN
-- adjust positions
SET #ChunkPos = #DelimPos + 1
END
-- find next delimiter
SET #DelimPos = CHARINDEX(#DelimChar, #Chunk, #ChunkPos)
END
-- adjust positions
SET #TextPos = #TextPos + #ChunkLen
END
-- handle last item
IF #ItemBegPos <= #InputLen
BEGIN
-- insert position
INSERT INTO #list_items (item_order, item_begpos, item_endpos)
VALUES (#ItemOrder, #ItemBegPos, #InputLen)
END
-- delete the bad items
DELETE FROM #list_items
WHERE item_endpos < item_begpos
-- return list items
SELECT SUBSTRING(#list_text, item_begpos, (item_endpos - item_begpos + 1)) AS item_text, item_order, item_begpos, item_endpos
FROM #list_items
ORDER BY item_order
END
DROP TABLE #list_items
RETURN
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
I have same idea with user KM. but do not need extra table Number. Just this function only.
CREATE FUNCTION [dbo].[FN_ListToTable]
(
#SplitOn char(1) --REQUIRED, the character to split the #List string on
,#List varchar(8000) --REQUIRED, the list to split apart
)
RETURNS
#ParsedList table
(
ListValue varchar(500)
)
AS
BEGIN
DECLARE #number int = 0
DECLARE #childString varchar(502) = ''
DECLARE #lengthChildString int = 0
DECLARE #processString varchar(502) = #SplitOn + #List + #SplitOn
WHILE #number < LEN(#processString)
BEGIN
SET #number = #number + 1
SET #lengthChildString = CHARINDEX(#SplitOn, #processString, #number + 1) - #number - 1
IF #lengthChildString > 0
BEGIN
SET #childString = LTRIM(RTRIM(SUBSTRING(#processString, #number + 1, #lengthChildString)))
IF #childString IS NOT NULL AND #childString != ''
BEGIN
INSERT INTO #ParsedList(ListValue) VALUES (#childString)
SET #number = #number + #lengthChildString - 1
END
END
END
RETURN
END
And here is the test:
SELECT ListValue FROM dbo.FN_ListToTable('/','a/////bb/c')
Result:
ListValue
______________________
a
bb
c
-- select * from dbo.Split_ID('77,106')
ALTER FUNCTION dbo.Split_ID(#String varchar(8000))
returns #temptable TABLE (ID varchar(8000))
as
begin
declare #idx int
declare #slice varchar(8000)
declare #Delimiter char(1)
set #Delimiter =','
select #idx = 1
if len(#String)<1 or #String is null return
while #idx!= 0
begin
set #idx = charindex(#Delimiter,#String)
if #idx!=0
set #slice = left(#String,#idx - 1)
else
set #slice = #String
if(len(#slice)>0)
insert into #temptable(ID) values(#slice)
set #String = right(#String,len(#String) - #idx)
if len(#String) = 0 break
end
return
end
You could do it like this:
create or replace
PROCEDURE UDP_SETBOOKMARK
(
P_USERID IN VARCHAR2
, P_BOOKMARK IN VARCHAR2
) AS
BEGIN
UPDATE T_ER_Bewertung
SET LESEZEICHEN = P_BOOKMARK
WHERE STAMM_ID in( select regexp_substr(P_USERID,'[^,]+', 1, level) from dual
connect by regexp_substr(P_USERID, '[^,]+', 1, level) is not null )
and ER_ID = (select max(ER_ID) from T_ER_Bewertung_Kopie);
commit;
END UDP_SETBOOKMARK;
Then try it with
Begin
UDP_SETBOOKMARK ('1,2,3,4,5', 'Test');
End;
You can use this IN-Clause with regexp_substr in other situations too, just try it.
Error 493: The column 'i' that was returned from the nodes() method cannot be
used directly. It can only be used with one of the four XML data type
methods, exist(), nodes(), query(), and value(), or in IS NULL and IS NOT
NULL checks.
The above errorr was fixed in SQL Server 2014 by using following snippet
Declare #Ids varchar(50)
Set #Ids = '1,2,3,5,4,6,7,98,234'
DECLARE #XML XML
SET #XML = CAST('<i>' + REPLACE(#Ids, ',', '</i><i>') + '</i>' AS XML)
SELECT SomeTable.*
FROM
SomeTable
cross apply #XML.nodes('i') x(i)
where SomeTable .Id = x.i.value('.', 'VARCHAR(MAX)')
Try this:
SELECT ProductId, Name, Tags
FROM Product
WHERE '1,2,3,' LIKE '%' + CAST(ProductId AS VARCHAR(20)) + ',%';
As said on the last example of this link
Tons of answers here, but to add my two cents I think STRING_SPLIT is a very simple approach to this sort of problem:
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE tableid IN;
(SELECT value FROM STRING_SPLIT(#Ids, ','))
Best and simple approach.
DECLARE #AccumulateKeywordCopy NVARCHAR(2000),#IDDupCopy NVARCHAR(50);
SET #AccumulateKeywordCopy ='';
SET #IDDupCopy ='';
SET #IDDup = (SELECT CONVERT(VARCHAR(MAX), <columnName>) FROM <tableName> WHERE <clause>)
SET #AccumulateKeywordCopy = ','+#AccumulateKeyword+',';
SET #IDDupCopy = ','+#IDDup +',';
SET #IDDupCheck = CHARINDEX(#IDDupCopy,#AccumulateKeywordCopy)
CREATE TABLE t
(
id INT,
col1 VARCHAR(50)
)
INSERT INTO t
VALUES (1,
'param1')
INSERT INTO t
VALUES (2,
'param2')
INSERT INTO t
VALUES (3,
'param3')
INSERT INTO t
VALUES (4,
'param4')
INSERT INTO t
VALUES (5,
'param5')
DECLARE #params VARCHAR(100)
SET #params = ',param1,param2,param3,'
SELECT *
FROM t
WHERE Charindex(',' + Cast(col1 AS VARCHAR(8000)) + ',', #params) > 0
working fiddle find here Fiddle
I ran into the same issue, and I don't want to have any footprint on the source database - i.e. no stored procedures or functions. I went about it this way:
declare #IDs table (Value int)
insert into #IDs values(1)
insert into #IDs values(2)
insert into #IDs values(3)
insert into #IDs values(5)
insert into #IDs values(4)
insert into #IDs values(6)
insert into #IDs values(7)
insert into #IDs values(98)
insert into #IDs values(234)
SELECT *
FROM sometable
WHERE tableid IN (select Value from #IDs)
The answer by #RBarryYoung (above) worked for me.
But when you have spaces in between the comma separated string values, then it will omit IDs with spaces. So I removed the spaces.
Take a look at the code snippet below.
Declare #Ids varchar(50) Set #Ids = '1 , 2,3'
set #Ids=','+Replace(#Ids,' ', '')+',';
Select * from [tblEmployee]
where Charindex(','+cast(ID as varchar(8000))+',', #Ids) > 0
WHERE someId IN (SELECT convert(int, value) FROM string_split(#stringOfCommaDelimitedIds, ','))
The simplest way i found was to use FIND_IN_SET
FIND_IN_SET(column_name, values)
values=(1,2,3)
SELECT name WHERE FIND_IN_SET(id, values)
This came in handy for one of my requirements where I did not want to use CTE and also did not want to go with the inner join.
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT
cn1,cn2,cn3
FROM tableName
WHERE columnName in (select Value from fn_SplitString(#ids, ','))
Function for split string :
CREATE FUNCTION [dbo].[fn_SplitString] ( #stringToSplit VARCHAR(MAX), #seperator Char )
RETURNS
#returnList TABLE ([Value] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(#seperator, #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(#seperator, #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END