嗨,我想将逗号分隔的nvarchar转换为sql中的int列表

时间:2017-05-29 09:29:08

标签: sql sql-server tsql sql-server-2005

我想将逗号分隔的nvarchar转换为sql中的int list.How我可以实现吗?

2 个答案:

答案 0 :(得分:0)

我创建了一个函数

    USE [QA]
    GO
    /****** Object:  UserDefinedFunction [dbo].[NvarcharToIntList]    Script Date: 5/29/2017 2:42:50 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO

    ALTER FUNCTION [dbo].[NvarcharToIntList] (@InStr VARCHAR(MAX))
    RETURNS @TempTab TABLE
       (id int not null)
    AS
    BEGIN
        ;-- Ensure input ends with comma
        SET @InStr = REPLACE(@InStr + ',', ',,', ',')
        DECLARE @SP INT
    DECLARE @VALUE VARCHAR(1000)
    WHILE PATINDEX('%,%', @INSTR ) <> 0 
    BEGIN
       SELECT  @SP = PATINDEX('%,%',@INSTR)
       SELECT  @VALUE = LEFT(@INSTR , @SP - 1)
       SELECT  @INSTR = STUFF(@INSTR, 1, @SP, '')
       INSERT INTO @TempTab(id) VALUES (@VALUE)
    END
        RETURN
    END
@users = '158,159'

然后我将其用作dbo.ResidentAssessment.LastUpdatedBy in(SELECT * FROM dbo.NvarcharToIntList(@users))

答案 1 :(得分:0)

从SQL 2016开始,有一个STRING_SPLIT函数

来自doc

DECLARE @tags NVARCHAR(400) = 'clothing,road,,touring,bike'  

SELECT value  
FROM STRING_SPLIT(@tags, ',');