将整数列表分配给@var

时间:2010-04-07 11:08:58

标签: tsql

我可以:

declare @idOrder int
set @idOrder = 21319

我想:

declare @idOrder int
set @idOrder = (21319, 21320)

用于'WHERE'子句使用IN运算符

的一系列语句中
delete Orders
where idOrder in @idOrder

而不是

delete Orders
where idOrder in (21319, 21320)

2 个答案:

答案 0 :(得分:6)

只要它是int,就不能这样做,因为那不是该数据类型的有效值。可能需要几个整数的数据类型是table

declare @idOrder table (id int)

insert into @idOrder values(21319)
insert into @idOrder values(21320)

delete from Orders where idOrder in (select id from @idOrder)

答案 1 :(得分:3)

在SQL Server中,您也可以

CREATE FUNCTION [dbo].[fn_ado_param_int] (@ado nvarchar(4000))
RETURNS @VALUES TABLE (ado int)AS
   BEGIN
   declare @Delim char(1)
   set @Delim = ','
   DECLARE @chrind INT
   DECLARE @Piece nvarchar(4000)
   SELECT @chrind = 1
   WHILE @chrind > 0
      BEGIN
         SELECT @chrind = CHARINDEX(@Delim,@ado)
         IF @chrind > 0
            SELECT @Piece = LEFT(@ado,@chrind - 1)
         ELSE
            SELECT @Piece = @ado
         INSERT @VALUES(ado) VALUES(@Piece)
         SELECT @ado = RIGHT(@ado,LEN(@ado) - @chrind)
         IF LEN(@ado) = 0 BREAK
      END
   RETURN
END

declare @idOrder varchar(500);
set @inOrder = "21319,2138,2138";
delete from Orders where id in (select ado from dbo.fn_ado_param_int(@idOrder));