T-SQL如何在WHERE IN子句中使用变量?

时间:2015-04-17 21:02:43

标签: sql-server

我能做到这一点并且有效(但想要更简单的事情):

Declare @PropIDs        varchar(50)
Set @PropIDs = '1, 2'

IF OBJECT_ID('dbo.TempProp') IS NOT NULL DROP TABLE dbo.TempProp

CREATE TABLE [dbo].[TempProp](
    [PropCode] [VarChar](3) NULL)

Set @Sql = 'Insert Into TempProp Select PropertyCode From Property where PropertyID In (' + @PropIDs + ')'

Execute (@Sql)

但我希望我能做到这一点:

Declare @PropIDs
Set @PropIDs = '1, 2'
Select PropertyCode 
Into #TempProp
From Property where PropertyID IN (@PropIDs)

这是“...属性IN(@PropIDs)”给我带来麻烦。 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

创建一个与此类似的分割表值函数

create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))       
returns @temptable TABLE (items varchar(MAX))       
as       
begin      
    declare @idx int       
    declare @slice varchar(8000)       

    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(@Delimiter,@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String       

        if(len(@slice)>0)  
            insert into @temptable(Items) values(@slice)       

        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break       
    end   
return 
end;

该代码来自此问题:separate comma separated values and store in table in sql server

然后在您的查询中使用它:

Declare @PropIDs
Set @PropIDs = '1, 2'
Select PropertyCode 
Into #TempProp
From Property where PropertyID IN (dbo.Slit(@PropIDs, ','))