表
Column A Column B Column C
----------------------------------------------
我有一个输入字符串,如(Apple,Banana,Orange)。我需要将这些值插入上表。
结果应该是
ColumnA Column B Column C
-------------------------------------------
Apple Banana Orange
是否可以使用将输入参数作为csv字符串的过程?
答案 0 :(得分:1)
请使用以下代码获取列名列表。您可以将其传递给SP以插入到您的表格中。
BEGIN
DECLARE @str VARCHAR(2000)
DECLARE @input VARCHAR(4000)
DECLARE @ind Int
DECLARE @Count int
DECLARE @max int
SET @max =0
DECLARE @table TABLE(ColumnA varchar(10),ColumnB varchar(10),ColumnC varchar(10))
DECLARE @Result TABLE (ID int identity(1,1),value varchar(1000))
SET @input ='Apple,Banana,Orange'
IF(@input is not null)
BEGIN
SET @ind = CharIndex(',',@input)
WHILE @ind > 0
BEGIN
SET @str = SUBSTRING(@input,1,@ind-1)
SET @input = SUBSTRING(@input,@ind+1,LEN(@input)-@ind)
INSERT INTO @Result values (@str)
SET @ind = CharIndex(',',@input)
END
SET @str = @input
INSERT INTO @Result values (@str)
END
SET @Count = (SELECT Max(ID) from @Result)
WHILE @Count > @max
BEGIN
SET @max = @max +1
DECLARE @Value varchar(1000)
SET @Value = (SELECT value from @Result WHERE ID =@max)
SELECT @value
END
END
答案 1 :(得分:0)
请检查以下SQL脚本,该脚本将输入字符串参数拆分并插入表
请注意我使用SQL split string function dbo.Split,你可以在推荐的SQL教程中找到源代码
除非使用SQL Server 2016
,否则您将需要这样的用户定义拆分功能/*
create table TableT (
[Column A] varchar(100),
[Column B] varchar(100),
[Column C] varchar(100)
)
*/
declare @string varchar(max) = 'Apple,Banana,Orange'
select * from dbo.Split(@string, ',')
insert into TableT
select
MAX([Column A]) as [Column A],
MAX([Column B]) as [Column B],
MAX([Column C]) as [Column C]
from (
select
case when id = 1 then val end as [Column A],
case when id = 2 then val end as [Column B],
case when id = 3 then val end as [Column C]
from dbo.Split(@string, ',')
) s
select * from TableT
答案 2 :(得分:-2)
请使用以下查询。它在SQL Server 2012中运行良好。
char