【问题标题】:T-SQL How can I use a variable in the WHERE IN clause? [duplicate]T-SQL 如何在 WHERE IN 子句中使用变量? [复制]
【发布时间】:2015-04-18 06:41:42
【问题描述】:

我可以做到这一点并且它有效(但想要更简单的东西):

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)

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

【问题讨论】:

  • 如果您的值在这样的列表中,那么您必须使用动态 SQL。
  • 我的意思是“...PropertyID IN (@PropIDs)”部分给我带来了麻烦
  • 使用表值参数而不是逗号分隔的字符串。这不是 JSON,它们是单独的值。

标签: sql-server


【解决方案1】:

创建一个类似这个的拆分表值函数

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, ','))

【讨论】:

    猜你喜欢
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2013-10-16
    • 2020-04-16
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多