Convert varchar list to int in Sql Server

ε祈祈猫儿з 提交于 2019-12-13 09:08:23

问题


I need a way to have the @listOfPageIds be recognized as a list of numbers instead of strings. I have tried casting, removing the single quotes... I really don't want to do a loop in sql.

Declare @listOfPageIds varchar(50) ;

Set @listofPageIds = '2, 3, 4, 5, 6, 7, 14, 15';

select * from mytable p where p.PageId in( @listOfPageIds);

回答1:


Well on production server I'd write some table valued function for splitting lists, but if you need quick ad-hoc query, this xml trick could work

declare @listOfPageIds varchar(50), @data xml
declare @temp table(id int)

select @listofPageIds = '2, 3, 4, 5, 6, 7, 14, 15';
select @data = '<t>' + replace(@listofPageIds, ', ', '</t><t>') + '</t>'

insert into @temp
select
    t.c.value('.', 'int') as id
from @data.nodes('t') as t(c)

select * from @temp

sql fiddle demo




回答2:


DECLARE @YourTable

DECLARE @yourTable TABLE (col1 INT);
INSERT INTO @yourTable VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15);

Dynamic SQL Solution

DECLARE @listOfPageIds nvarchar(255);
SET @listOfPageIds = '2, 3, 4, 5, 6, 7, 14, 15'
EXEC
(
'
DECLARE @yourTable TABLE (col1 INT);
INSERT INTO @yourTable VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
SELECT *
FROM @yourTable
WHERE col1 IN (' + @listOfPageIds+ ')'
)

Recursive CTE Solution

DECLARE @listOfPageIds nvarchar(255);
SET @listOfPageIds = '2, 3, 4, 5, 6, 7, 14, 15'
SET @listOfPageIds = REPLACE(@listOfPageIds,' ','') + ',';  -- Put the end comma there instead of having to use a case statement in my query
                                                            -- As well as getting rid of useless white space with REPLACE()

WITH CTE
AS
(
    SELECT 1 row_count, CAST(SUBSTRING(@listOfPageIds,0,CHARINDEX(N',',@listOfPageIds,0)) AS NVARCHAR(255)) AS search_val, CHARINDEX(',',@listOfPageIds,0) + 1 AS starting_position
    UNION ALL
    SELECT row_count + 1,CAST(SUBSTRING(@listOfPageIds,starting_position,CHARINDEX(',',@listOfPageIds,starting_position) - starting_position) AS NVARCHAR(255)) AS search_val, CHARINDEX(',',@listOfPageIds,starting_position) + 1 AS starting_position
    FROM CTE
    WHERE row_count < (LEN(@listOfPageIds) - LEN(REPLACE(@listOfPageIds,',','')))
)

SELECT *
FROM @yourTable
WHERE col1 IN (SELECT CAST(search_val AS INT) FROM CTE)

Results(@yourTable has values 1-15):

col1
-----------
2
3
4
5
6
7
14
15


来源:https://stackoverflow.com/questions/29680931/convert-varchar-list-to-int-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!