Sql server T-SQL如何在WHERE in子句中使用变量?
我可以做到这一点,它的工作(但想更简单的东西): 但我希望我能做到这一点:Sql server T-SQL如何在WHERE in子句中使用变量?,sql-server,Sql Server,我可以做到这一点,它的工作(但想更简单的东西): 但我希望我能做到这一点: Declare @PropIDs Set @PropIDs = '1, 2' Select PropertyCode Into #TempProp From Property where PropertyID IN (@PropIDs) 正是(@PropIDs)中的“…属性”给我带来了麻烦。 有什么建议吗?创建一个类似于此的拆分表值函数 create FUNCTION [dbo].[Split](@String va
Declare @PropIDs
Set @PropIDs = '1, 2'
Select PropertyCode
Into #TempProp
From Property where PropertyID IN (@PropIDs)
正是(@PropIDs)中的“…属性”给我带来了麻烦。
有什么建议吗?创建一个类似于此的拆分表值函数
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;
如果您的值在这样的列表中,那么您必须使用动态SQL。我的意思是“…PropertyID in(@PropIDs)”部分给了我麻烦使用表值参数而不是逗号分隔的字符串。这不是JSON,它们是单独的值。
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;
Declare @PropIDs
Set @PropIDs = '1, 2'
Select PropertyCode
Into #TempProp
From Property where PropertyID IN (dbo.Slit(@PropIDs, ','))