如何将在varchar中格式化的ID列表转换为int

时间:2015-02-13 09:08:40

标签: sql sql-server

我在SQL Server中将ID列表varchar转换为整数以用作参数时出现问题。我知道如果你这样做会有效:

SELECT * 
FROM MyTable 
WHERE MyTableId IN (26,27,28)` --list of IDs to be selected

但将此ID列表放在varchar中,因为我希望我的参数是动态的,会返回一些错误。 我的代码是这样的:

DECLARE @ids varchar(100)
SET @ids = '26,27,28'

SELECT * 
FROM MyTable 
WHERE MyTableId in (@ids)  --(26,27,28)`

它不起作用,因为MyTableId是数据类型int

1 个答案:

答案 0 :(得分:0)

您必须将逗号分隔值覆盖到表格。为SQL SERVER执行此操作

CREATE FUNCTION SplitString
(    
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
)
RETURNS @Output TABLE (
      Item 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(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)

            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
      END

      RETURN
END


SELECT * FROM MyTable where MyTableId in 
      (SELECT * FROM dbo.SplitString('26,27,28', ','))  --(26,27,28)