How to format XML after fetching from table in sql server - sql

I have a requirement where I have to format XML structure coming from following output:
DECLARE #cousumptionFileName VARCHAR(50)
DECLARE #sqlCmd VARCHAR(1000)
DECLARE #sqlConStr VARCHAR(1000)
SET #cousumptionFileName = 'C:\export\IDE\Consumption.xml' -- SELECT * FROM ' + DB_NAME()+'.dbo.ReadingData
SET #sqlConStr = 'select top 10 * from [FixedNetworkist].[dbo].[ConsumptionReading0] order by deviceid FOR XML AUTO'
SET #sqlCmd = 'bcp "' + #sqlConStr + '" queryout ' + #cousumptionFileName + ' -w -T'
EXEC xp_cmdshell #sqlCmd
The output is:
<Reading0 RecordId="14452573" PartitionSequence="1" DeviceId="1015" DeviceType="13" CollectorId="74045037" CollectorType="120" Reading="0" ReadingDateTime="2019-01-21T01:15:00" PresentationInterval="15" RecordEpochTime="-599450337"/>
<Reading0 RecordId="14452859" PartitionSequence="1" DeviceId="1015" DeviceType="13" CollectorId="51000666" CollectorType="120" ChannelNumber="1" Reading="0" IntervalStatus="0" ReadingDateTime="2019-01-21T01:15:00" PresentationInterval="15" RecordEpochTime="-599450335"/>
I want this to be structure like to avoid the repetitive value:
<Reading0 PartitionSequence="1" DeviceId="1015" DeviceType="13" ChannelNumber="1" >
<Readings>
<Reading RecordId="14452573" CollectorId="74045037" Reading="0" ReadingDateTime="2019-01-21T00:29:58" RecordEpochTime="-599453037" />
<Reading RecordId="14452859" CollectorId="51000666" Reading="0" ReadingDateTime="2019-01-21T00:29:58" RecordEpochTime="-599453037" />
</Readings>
Could anyone help me to achieve this?

For your transformation consider the use of 'FOR XML EXPLICIT', instead of 'FOR XML AUTO'. Good article to read more about:
https://learn.microsoft.com/en-us/sql/relational-databases/xml/use-explicit-mode-with-for-xml?view=sql-server-2017
My sample data:
DECLARE #Reading TABLE ( PartitionSequence int, DeviceId int, DeviceType int, ChannelNumber int,CollectorId int,RecordId int, Reading int, ReadingDateTime datetime, RecordEpochTime int)
INSERT INTO #Reading ( PartitionSequence, DeviceId , DeviceType, ChannelNumber,CollectorId , RecordId, Reading, ReadingDateTime, RecordEpochTime )
VALUES
(1,1015,13,1,1,14452573,0,'2019-01-21T00:29:58',-599453037)
,(1,1015,13,1,1,51000666,0,'2019-01-21T00:29:58',-599453037)
Sql query:
SELECT
1 AS Tag
,NULL AS parent
,r.PartitionSequence AS [Readings!1!PartitionSequence]
,r.DeviceId AS [Readings!1!DeviceId]
,r.DeviceType AS [Readings!1!DeviceType]
,r.ChannelNumber AS [Readings!1!ChannelNumber]
,NULL AS [Reading!2!RecordId]
,NULL AS [Reading!2!Reading]
,NULL AS [Reading!2!ReadingDateTime]
,NULL AS [Reading!2!RecordEpochTime]
FROM #Reading r
UNION
SELECT
2 AS Tag
,1 AS parent
,r.PartitionSequence
,r.DeviceId
,r.DeviceType
,r.ChannelNumber
,r.RecordId
,r.Reading
,r.ReadingDateTime
,r.RecordEpochTime
FROM #Reading r
FOR XML EXPLICIT
Result of the query:
<Readings PartitionSequence="1" DeviceId="1015" DeviceType="13" ChannelNumber="1">
<Reading RecordId="14452573" Reading="0" ReadingDateTime="2019-01-21T00:29:58" RecordEpochTime="-599453037" />
<Reading RecordId="51000666" Reading="0" ReadingDateTime="2019-01-21T00:29:58" RecordEpochTime="-599453037" />
</Readings>

Related

How to parse XML file in a folder with dynamic t-sql?

I'd like to change this XML to SQL statement below to work with a path rather than a file name, at the moment it's looking for 'C:\Test\XML\PT38.xml'.
I need it to parse any .XML file in the folder rather than look for a specific one. It will be just one file at a time but they'll have different names (number increase: PT39, PT40, etc.).
I tried adding a variable for the path then changing the BULK to look for the variable, but it failed as expected.
I've read something about creating a temporary table then parse the date, but I'm not sure that would work for me.
I'd appreciate the help.
This is what I tried:
DECLARE #xmlFileName varchar(100) = 'C:\Test\XML\'
FROM OPENROWSET(BULK ''' + #xmlFileName + ''', SINGLE_BLOB) AS T(MY_XML)) AS T(MY_XML)
This is the XML content:
<?xml version="1.0" encoding="UTF-8" ?>
<MOD1>
<DC BEGIN="1">
<DC4 SEGMENT="1">
<TABNAM>DC4</TABNAM>
<DOCNUM>0000003899888135</DOCNUM>
</DC4>
<ZPR SEGMENT="1">
<AUFNR>000915229446</AUFNR>
<LNO>RM01PL01</LNO>
<CHARG>0006186588</CHARG>
<STR2>211609</STR2>
<QTY>4166.000</QTY>
<PLN_ORDER>6963701111</PLN_ORDER>
</ZPR>
</DC>
</MOD1>
This is the SQL table:
CREATE TABLE XMLTESTTABLE
(
PON int,
ASP int,
LTN varchar(11),
GAS int,
QY varchar(15),
LNO varchar(2),
StartTime date,
);
This is the statement:
INSERT INTO XMLTESTTABLE(PON, ASP, LTN, GAS, QY, LNO, StartTime)
SELECT ZPRM.value('(AUFNR/text())[1]', 'int')
, ZPRM.value('(CHARG/text())[1]', 'int')
, ZPRM.value('(PLN_ORDER/text())[1]', 'VARCHAR(10)')
, ZPRM.value('(CHARG/text())[1]', 'int')
, ZPRM.value('(QTY/text())[1]', 'DECIMAL(10,0)') AS [qty]
, RIGHT(ZPRM.value('(LNO/text())[1]', 'VARCHAR(10)'), 2) AS [LNO]
, TRY_CAST(STUFF(STUFF(ZPRM.value('(STR2/text())[1]', 'CHAR(6)'),3,0,':'),6,0,':') AS TIME)
FROM (SELECT TRY_CAST(MY_XML AS xml)
FROM OPENROWSET(BULK 'C:\Test\XML\PT38.xml', SINGLE_BLOB) AS T(MY_XML)) AS T(MY_XML)
CROSS APPLY MY_XML.nodes('/MOD1/DC/ZPR') AS MY_XML(ZPRM);
It is much easier to implement in SQL Server 2017 and later. It has much better API to deal with the file system.
Please try the following solution. It will work in SQL Server 2012.
I modified the StartTime column data type as TIME(0).
You would need to modify #folder variable value to match what you have in your environment.
SQL
USE tempdb;
GO
DROP TABLE IF EXISTS dbo.XMLTESTTABLE;
CREATE TABLE dbo.XMLTESTTABLE
(
PON varchar(10),
ASP int,
LTN varchar(11),
GAS int,
QY varchar(15),
LNO varchar(2),
StartTime TIME(0)
);
DECLARE #xml XML
, #sql NVARCHAR(MAX)
, #XMLfileName VARCHAR(256) -- 'e:\Temp\TradeFeed\PT38.xml';
, #folder VARCHAR(256) = 'e:\Temp\TradeFeed';
DECLARE #tbl TABLE (
id INT IDENTITY(1,1) PRIMARY KEY,
[fileName] VARCHAR(512),
depth INT,
isfile BIT
);
INSERT INTO #tbl ([fileName], depth, isfile)
EXEC master.sys.xp_dirtree #folder,1,1;
-- just to see
SELECT * FROM #tbl;
-- filter out not need files
SELECT TOP(1) #XMLfileName = CONCAT(#folder, '\', [fileName])
FROM #tbl
WHERE isfile = 1
AND [fileName] LIKE '%.xml';
SET #sql = N'SELECT #xmlOut = XmlDoc FROM OPENROWSET (BULK ' + QUOTENAME(#XMLfileName,NCHAR(39)) + ', SINGLE_BLOB) AS Tab(XmlDoc)';
EXEC master.sys.sp_executesql #sql, N'#xmlOut XML OUTPUT', #xmlOut = #xml OUTPUT;
INSERT INTO XMLTESTTABLE(PON, ASP, LTN, GAS, QY, LNO, StartTime)
SELECT #xml.value('(/MOD1/DC/DC4/TABNAM/text())[1]', 'VARCHAR(10)')
, c.value('(CHARG/text())[1]', 'int')
, c.value('(PLN_ORDER/text())[1]', 'VARCHAR(10)')
, c.value('(CHARG/text())[1]', 'int')
, c.value('(QTY/text())[1]', 'DECIMAL(10,0)') AS [qty]
, RIGHT(c.value('(LNO/text())[1]', 'VARCHAR(10)'), 2) AS [LNO]
, TRY_CAST(STUFF(STUFF(c.value('(STR2/text())[1]', 'CHAR(6)'),3,0,':'),6,0,':') AS TIME(0))
FROM #xml.nodes('/MOD1/DC/ZPR') AS t(c);
-- test
SELECT * FROM dbo.XMLTESTTABLE;
Output
+-----------+---------+------------+---------+------+-----+-----------+
| PON | ASP | LTN | GAS | QY | LNO | StartTime |
+-----------+---------+------------+---------+------+-----+-----------+
| DC4 | 6186588 | 6963701111 | 6186588 | 4166 | 01 | 21:16:09 |
+-----------+---------+------------+---------+------+-----+-----------+

Dynamically create table columns with values from Pivot Table

I have a dynamic query that utilizes a pivot function and the following is an example of data in my table.
Status 1 | Week 1 |25
Status 1 | Week 1 |25
Status 1 | Week 2 |25
Status 2 | Week 1 | 2
Status 2 | Week 1 | 8
Status 2 | Week 1 | 10
Status 2 | Week 1 | 10
and this is an example of how the data is returned.
Week 1 Week 2
Status 1 | 50 25
Status 2 10 20
For my query I am passing in a week and I want to pivot on the following 5 weeks, so example, if I pass in 1, I expect to have columns from week 1 to week 6.
To help facilitate that I have written the following query.
--EXEC usp_weekReport #weeks=1, #year='2019'
ALTER PROC usp_weekReport
(
#weeks INT,
#year NVARCHAR(4)
)
AS
DECLARE #columns NVARCHAR(MAX), #sql NVARCHAR(MAX), #csql NVARCHAR(MAX);
SET #columns = N'';
SELECT #columns += N', p.' + QUOTENAME([week])
FROM (
SELECT p.[week]
FROM [Housing_support_DB].[dbo].[Invoices] P
WHERE DATEPART(YEAR,P.date)='2019'--#year
AND
([week] IN (1)
OR
[week] IN (1+1)
OR
[week] IN (1+2)
OR
[week] IN (1+3)
OR
[week] IN (1+4)
OR
[week] IN (1+5)
)
GROUP BY P.[week]
) AS x;
SET #sql = N'
SELECT p.[statusName],' + STUFF(#columns, 1, 2, '') + '
FROM
(
SELECT
SUM(CAST(REPLACE(REPLACE(A.amount,'','',''''),''$'','''') AS FLOAT)) as sumInvoice,
A.invoiceStatusID_FK,
B.statusName,
-- C.programme,
[week]
FROM [dbo].[Invoices] A
INNER JOIN invoiceStatus B
ON A.invoiceStatusID_FK=B.invoiceStatusID
-- INNER JOIN CapitalAccountBalances C
-- ON C.accountBalanceID=A.accountBalanceID_FK
-- WHERE A.accountBalanceID_FK=5
GROUP BY invoiceStatusID_FK,B.statusName,[week]--,C.programme
) AS j
PIVOT
(
SUM(sumInvoice) FOR [week] IN ('
+ STUFF(REPLACE(#columns, ', p.[', ',['), 1, 1, '')
+ ')
) AS p;';
--PRINT #sql;
EXEC sp_executesql #sql;
--SET #csql = N'
--CREATE TABLE ##reportResult
--(
--statusName nvarchar(50),'+
CREATE TABLE ##reportResult
(
statusName nvarchar(50),
weekA INT DEFAULT 0,
weekB int DEFAULT 0--,
--weekC int DEFAULT 0,
--weekD int DEFAULT 0,
--weekE int DEFAULT 0,
--weekF int DEFAULT 0
)
INSERT into ##reportResult Exec(#sql)
--INSERT ##reportResult Exec(#sql)
--SELECT statusName, weekA,weekB,weekC,weekD,weekE,weekF -- here you have "static SELECT with field names"
--FROM ##reportResult
--DROP TABLE ##reportResult
Problem
The huge problem that I have here is that, I need to send the result of this query to a tempTable...#reportResult. As a result, I need to create the table. However, if I attempt to create the table with the max amount of columns anticipated (6) I will get an invalid number of columns error. For example, in my database I only have two weeks, that's why I can only create the table with columns weekA and weekB. I also cannot do a select into.
Presently, I am trying to find a way to either create the table dynamically depending on the amount of weeks from the first part of the pivot table. Or, to manipulate the first part of the pivot to select week,week+1 etc as columns when run so that way , I can create the column with all fields.
Appreciate any help that could be provided.
You required dynamic SQL in your case as the column name is need to generate based on th Input week number. Below I have give you the script I created with your sample data using CTE. You just need to updated the script based on your table and requirement.
You can test the code changing the value of Week_No
For your final query, just use the SELECT part after removing the CTE code
DECLARE #Week_No INT = 2
DECLARE #Loop_Count INT = 1
DECLARE #Column_List VARCHAR(MAX) = '[Week '+CAST(#Week_No AS VARCHAR) +']'
WHILE #Loop_Count < 5
BEGIN
SET #Column_List = #Column_List +',[Week '+CAST(#Week_No+#Loop_Count AS VARCHAR) +']'
SET #Loop_Count = #Loop_Count + 1
END
--SELECT #Column_List
EXEC
('
WITH your_table(Status,Week_No,Val)
AS
(
SELECT ''Status 1'',''Week 1'',25 UNION ALL
SELECT ''Status 1'',''Week 1'',25 UNION ALL
SELECT ''Status 1'',''Week 2'',25 UNION ALL
SELECT ''Status 2'',''Week 1'',2 UNION ALL
SELECT ''Status 2'',''Week 1'',8 UNION ALL
SELECT ''Status 2'',''Week 1'',10 UNION ALL
SELECT ''Status 2'',''Week 1'',10
)
SELECT * FROM
(
SELECT * FROM your_table
) AS P
PIVOT
(
SUM(val)
FOR Week_No IN ('+#Column_List+')
)PVT
')

Sql Server - For XML - Get null value from element

I am trying to replace the null xml element into the null value while doing the concatenation. And i am making some silly mistake. I want to differentiate between an empty value and null value. I am using OpenXML to parse the XML data and something is missing in the code to read the null based param element.
I am using Server Server 2014.
Please suggest.
DECLARE #message_body XML;
DECLARE #XMLParameterData Table
(SeqID INT Identity(1,1),
ParamValue varchar(max))
DECLARE #docRef int
DECLARE #dataPath nvarchar(255)
DECLARE #mappingType int = 2 --Element-Centric mapping
Select #message_body = N'<AsyncRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ParamList> <Param>Bruce</Param>
<Param>Wa''yne</Param>
<Param>Bruce#karan.com</Param>
<Param>Coke</Param>
<Param>20000</Param>
<Param xsi:nil="true"/>
<Param></Param>
</ParamList>
</AsyncRequest>';
Set #dataPath = '/AsyncRequest/ParamList/Param'
EXEC sp_xml_preparedocument #docRef output, #message_body
INSERT INTO #XMLParameterData(ParamValue)
Select * From OpenXML(#docRef, #dataPath, #mappingType)
WITH
(
valx varchar(max) '.'
)
-- the xml document ref needs to be released ASAP
EXEC sp_xml_removedocument #docRef
SELECT * From #XMLParameterData
DECLARE #CSVString varchar(max)
SELECT #CSVString = STUFF(
(SELECT ', ' +
CHAR(34) + ParamValue + CHAR(34)
FROM #XMLParameterData
ORDER BY SeqID
FOR XML PATH('')
), 1, 1, '')
SELECT #CSVString as CSVTest
Output :-
"Bruce", "Wa'yne", "Bruce#karan.com", "Coke", "20000", "", ""
Desired output :-
"Bruce", "Wa'yne", "Bruce#karan.com", "Coke", "20000", NULL, ""
Keep it simple! Use CASE WHEN to check if #xsi:nil="true" and .nodes instead of OPENXML:
DECLARE #message_body XML,
#output nvarchar(max);
select #message_body = N'<AsyncRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ParamList>
<Param>Bruce</Param>
<Param>Wa''yne</Param>
<Param>Bruce#karan.com</Param>
<Param>Coke</Param>
<Param>20000</Param>
<Param xsi:nil="true"/>
<Param></Param>
</ParamList>
</AsyncRequest>';
SELECT #output = STUFF((
SELECT
CASE WHEN t.v.value('#xsi:nil','nvarchar(max)') = 'true' THEN ',NULL'
ELSE ',"'+t.v.value('.','nvarchar(max)') + '"'
END
FROM #message_body.nodes('AsyncRequest/ParamList/Param') as t(v)
FOR XML PATH('')
),1,1,'')
SELECT #output
Will return:
"Bruce","Wa'yne","Bruce#karan.com","Coke","20000",NULL,""
How about this (I have slightly simplified your code by using xml.nodes rather than an xml document).
It uses the xml query expression .[not(#xsi:nil = "true")] to return a null where xsi:nil is true.
I then use COALESCE to return the string 'NULL' when a NULL is returned:
DECLARE #message_body XML;
DECLARE #XMLParameterData Table
(SeqID INT Identity(1,1),
ParamValue varchar(max))
Select #message_body = N'<AsyncRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><ParamList><Param>Bruce</Param><Param>Wa''yne</Param>
<Param>Bruce#karan.com</Param>
<Param>Coke</Param>
<Param>20000</Param>
<Param xsi:nil="true"/>
<Param></Param>
</ParamList>
</AsyncRequest>';
INSERT INTO #XMLParameterData(ParamValue)
SELECT T.c.value('.[not(#xsi:nil = "true")]', 'varchar(max)') AS result
FROM #message_body.nodes('/AsyncRequest/ParamList/Param')T(c)
SELECT * From #XMLParameterData
DECLARE #CSVString varchar(max)
SELECT #CSVString = STUFF(
(SELECT ', ' +
CHAR(34) + COALESCE(ParamValue, 'NULL') + CHAR(34)
FROM #XMLParameterData
ORDER BY SeqID
FOR XML PATH('')
), 1, 1, '')
SELECT #CSVString as CSVTest
This returns:
"Bruce", "Wa'yne", "Bruce#karan.com", "Coke", "20000", "NULL", ""
What are you trying to achieve is not a standard behavior. You propbably expect following:
DECLARE #message_body XML = N'<AsyncRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ParamList>
<Param>Bruce</Param>
<Param>Wa''yne</Param>
<Param>Bruce#karan.com</Param>
<Param>Coke</Param>
<Param>20000</Param>
<Param xsi:nil="true"/>
<Param></Param>
</ParamList>
</AsyncRequest>';
SELECT X.value('.[not(#xsi:nil="true")]', 'nvarchar(MAX)') Value
FROM #message_body.nodes('//Param') T(X)
Which yields:
Value
-----
Bruce
Wa'yne
Bruce#karan.com
Coke
20000
NULL
(empty string here)
You may want text from nodes, which is more standarized:
SELECT X.value('text()[1]', 'nvarchar(MAX)') Value
FROM #message_body.nodes('//Param') T(X)
Value
-----
Bruce
Wa'yne
Bruce#karan.com
Coke
20000
NULL
NULL
Note that <element/> and <element></element> are synonyms. It's empty, no matter how you write. Ask yourself: is first <element/> empty string? That would lead to long discussion - it's all a matter of interpretation. You may also consider xml:space attribute to handle whitespaces.

Concatenate XML variables in SQL Server

I have a query in a stored procedure retrieving some data in XML format to be returned in a variable #xml_data, like this:
SELECT #xml_data = (
SELECT * FROM (
SELECT 1 AS Tag
,0 AS Parent
.....
FROM MyTable
WHERE id = #id
UNION ALL
SELECT 2 AS Tag
,1 AS Parent
....
FROM MyTable2
WHERE id = #id
UNION ALL
SELECT 3 AS Tag
,2 AS Parent
....
FROM MyTable3
WHERE id = #id
) results
FOR XML EXPLICIT, TYPE)
This is working like the proverbial dream :)
However, I'd like to concatenate a header to this XML (e.g. <xml version="1.0" encoding="ISO-8859-1"/>) and can't figure out how to do it. I've tried converting to NVARCHAR, selecting the two variables in one statement but can't seem to get it right.
Can anyone help??
Thanks :)
Try doing like this:
DECLARE #x xml
DECLARE #strXML varchar(MAX)
SET #x=N'<Employee><Name>Luftwaffe</Name></Employee>'
set #strXML = '<xml version="1.0" encoding="ISO-8859-1"/>' + CONVERT(varchar(MAX),#x)
SELECT #strXML
Hope it helps !
You can just declare the string at the beginning and concatenate them together:
declare #xml_data nvarchar(MAX)
set #xml_data = '<xml version="1.0" encoding="ISO-8859-1"/>'
SELECT #xml_data = #xml_data + (
SELECT * FROM (
SELECT 1 AS Tag
,0 AS Parent
.....
FROM MyTable
WHERE id = #id
UNION ALL
SELECT 2 AS Tag
,1 AS Parent
....
FROM MyTable2
WHERE id = #id
UNION ALL
SELECT 3 AS Tag
,2 AS Parent
....
FROM MyTable3
WHERE id = #id
) results
FOR XML EXPLICIT, TYPE)
This is the easiest way, in my opinion:
declare #xml1 xml
declare #xml2 xml
declare #xml3 xml
select #xml1='<name>testname</name>'
select #xml2='<value>testvalue</value>'
select #xml3 =
(
select #xml1 AS xml1, #xml2 AS xml2
for xml path('')
)
select #xml3

SQL in (#Variable) query

I have the following code, the problem is that my variable list #LocationList is essentially a csv string. When I use this as part of the where LocationID in (#LocationList) it says its not an int (LocationID is an int). How can I get this csv string to be accepted by teh in clause?
Declare #LocationList varchar(1000)
Set #LocationList = '1,32'
select Locations from table where Where LocationID in (#LocationList)
The most efficient way to do this is with Dynamic SQL such as rt2800 mentions (with injection warnings by Michael Allen)
However you can make a function:
ALTER FUNCTION [dbo].[CSVStringsToTable_fn] ( #array VARCHAR(8000) )
RETURNS #Table TABLE ( value VARCHAR(100) )
AS
BEGIN
DECLARE #separator_position INTEGER,
#array_value VARCHAR(8000)
SET #array = #array + ','
WHILE PATINDEX('%,%', #array) <> 0
BEGIN
SELECT #separator_position = PATINDEX('%,%', #array)
SELECT #array_value = LEFT(#array, #separator_position - 1)
INSERT #Table
VALUES ( #array_value )
SELECT #array = STUFF(#array, 1, #separator_position, '')
END
RETURN
END
and select from it:
DECLARE #LocationList VARCHAR(1000)
SET #LocationList = '1,32'
SELECT Locations
FROM table
WHERE LocationID IN ( SELECT *
FROM dbo.CSVStringsToTable_fn(#LocationList) )
OR
SELECT Locations
FROM table loc
INNER JOIN dbo.CSVStringsToTable_fn(#LocationList) list
ON list.value = loc.LocationID
Which is extremely helpful when you attempt to send a multi-value list from SSRS to a PROC.
I often have this requirement, and SOMETIME, if you know very well the column you are searching on [the size/format/length], you can do a kind of REGEX.
Something like this :
DECLARE #MyListOfLocation varchar(255)
set #MyListOfLocation = '|1|32|36|24|3|'
Select LocationID
from Table
where #MyListOfLocation like '%|' + LocationID + '|%'
NOTE : the PIPE character is used to protect the query from returning any LocationID that contains a single character (the '1', for example).
Here is a complete working example :
DECLARE #MyListOfLocation varchar(255)
set #MyListOfLocation = '|1|11|21|'
SELECT LocationName
FROM (
select '1' as LocationID, 'My Location 1' as LocationName
union all
select '11' as LocationID, 'My Location 11' as LocationName
union all
select '12' as LocationID, 'My Location 12' as LocationName
union all
select '13' as LocationID, 'My Location 13' as LocationName
union all
select '21' as LocationID, 'My Location 21' as LocationName
) as MySub
where #MyListOfLocation like '%|' + LocationID + '|%'
WARNING! This method is not Index friendly!
If you want do add some IN(#MyListOfLocation) in all that, to leverage use of INDEXES, you can modify your script do to :
SELECT MyDATA.*
FROM HugeTableWithAnIndexOnLocationID as MyDATA
WHERE LocationID in (
Select LocationID
from Table
where #MyListOfLocation like '%|' + LocationID + '|%')
declare #querytext Nvarchar(MAX)
set #querytext = 'select Locations from table where Where LocationID in (' + #LocationList + ');';
exec sp_executesql #querytext;