declare @List varchar(25) = '2,3,4'
declare @Delinquencies table (id int);
insert into @Delinquencies(id) values('2'),('3'),('4'); --Line in question
@List
正在填充从SSRS报告中填充的字符串,并为其选择了哪些选项。现在我的存储过程的运行方式,我需要能够根据varchar列表的内容插入到我的表变量中。如何使用动态varchar列表插入表变量?这里列出的内容与我可以接近的测试格式非常接近。
我正在使用SQL Server 2008。
实施例
@List = '1'
insert into @Delinquencies(id) values('1')
任何组合
@List = '1,2,3,4'
insert into @Delinquencies(id) values('1'),('2'),('3'),('4')
答案 0 :(得分:4)
使用其中一个分割string functions from here ..
declare @List varchar(25) = '2,3,4';
declare @Delinquencies table (id int);
;with cte
as
(select * from
[dbo].[SplitStrings_Numbers](@list,',')
)
insert into @Delinquencies(id)
select * from cte
答案 1 :(得分:0)
你需要创建一个dbo.StringSplit
函数
采用两个参数(字符串,分隔符)
CREATE function [dbo].[StringSplit](
@String varchar (max),
@Delimiter nvarchar (10)
)
returns @ValueTable table ([Value] varchar(max))
begin
declare @NextString varchar(max)
declare @Pos int
declare @NextPos int
declare @CommaCheck nvarchar(1)
--Initialize
set @NextString = ''
set @CommaCheck = right(@String,1)
--Check for trailing Comma, if not exists, INSERT
--if (@CommaCheck <> @Delimiter )
set @String = @String + @Delimiter
--Get position of first Comma
set @Pos = charindex(@Delimiter,@String)
set @NextPos = 1
--Loop while there is still a comma in the String of levels
while (@pos <> 0)
begin
set @NextString = substring(@String,1,@Pos - 1)
insert into @ValueTable ( [Value]) Values (@NextString)
set @String = substring(@String,@pos +1,len(@String))
set @NextPos = @Pos
set @pos = charindex(@Delimiter,@String)
end
return
end
然后你可以像下面那样使用它
declare @List varchar(25) = '2,3,4'
SELECT value from dbo.StringSplit(@List,',')
答案 2 :(得分:0)
这是一个返回序列的解析器。
例如:
Select * from [dbo].[udf-Str-Parse]('126,256,512',',')
返回
Key_PS Key_Value
1 126
2 256
3 512
UDF
CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimeter varchar(10))
--Usage: Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
-- Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
Returns @ReturnTable Table (Key_PS int IDENTITY(1,1), Key_Value varchar(max))
As
Begin
Declare @XML xml;Set @XML = Cast('<x>' + Replace(@String,@Delimeter,'</x><x>')+'</x>' as XML)
Insert Into @ReturnTable Select Key_Value = ltrim(rtrim(String.value('.', 'varchar(max)'))) FROM @XML.nodes('x') as T(String)
Return
End