I am writing a SELECT
query that has multiple id, and I have to manually add '',''
(e.g '12L','22C'
).
I have around 2000 id in an Excel sheet.
Is there any quicker way to add ”,” to all the ID?
x
SELECT id, name
FROM table
WHERE id IN ('12L', '22C', 33j, 7k, 44J, 234C)
Advertisement
Answer
Here is a conceptual example for you. It will work in SQL Server 2012 onwards.
It is a three step process:
- Convert input string into XML.
- Convert XML into a relational resultset inside the CTE.
- Join with a DB table.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, Code VARCHAR(10), City VARCHAR(50));
INSERT INTO @tbl (Code, City) VALUES
('10T', 'Miami'),
('45L', 'Orlando'),
('50Z', 'Dallas'),
('70W', 'Houston');
-- DDL and sample data population, end
DECLARE @Str VARCHAR(100) = '22C,45L,50Z,105M'
, @separator CHAR(1) = ',';
DECLARE @parameter XML = TRY_CAST('<root><r><![CDATA[' +
REPLACE(@Str, @separator, ']]></r><r><![CDATA[') +
']]></r></root>' AS XML);
;WITH rs AS
(
SELECT c.value('.', 'VARCHAR(10)') AS Code
FROM @parameter.nodes('/root/r/text()') AS t(c)
)
SELECT t.*
FROM @tbl AS t INNER JOIN
rs ON t.Code = rs.Code;