有没有办法从变量中将数据插入表中?可变内容示例:
123;1;500;some text here;
145;0;250;and some more text;
146;1;0;;
146;0;3;this field in previous line is empty;
;
\r\n
答案 0 :(得分:2)
如果; - 已分隔内容位于文件中,则可以使用BULK INSERT。有关此问题的StackOverflow问题,您可以找到here。因此,将变量的内容转储到文件中并使用BULK INSERT将是一种方法。
答案 1 :(得分:0)
解决方案就像......
declare @var varchar(100)
set @var= '123;1;500;some text here;'
select @var as variable,CHARINDEX(';',@var) as col1
,CHARINDEX(';',@var,CHARINDEX(';',@var)+1) as col2
,CHARINDEX(';',@var,CHARINDEX(';',@var,CHARINDEX(';',@var)+1)+1) as col3
,CHARINDEX(';',@var,CHARINDEX(';',@var,CHARINDEX(';',@var,CHARINDEX(';',@var)+1)+1)+1) as col4
into #temp
select * from #temp
select SUBSTRING(variable,0,col1) as Col1Text
,replace(SUBSTRING(variable,col1,col2-col1),';','') as Col2Text
,replace(SUBSTRING(variable,col2,col3-col2),';','') as Col2Text
,replace(SUBSTRING(variable,col3,col4-col3),';','') as Col2Text
from #temp
drop table #temp
答案 2 :(得分:0)
DECLARE @table_var TABLE(
col_list VARCHAR(50)
)
INSERT INTO @table_var VALUES ('123;1;500;some text here');
INSERT INTO @table_var VALUES ('145;0;250;and some more text;');
INSERT INTO @table_var VALUES ('146;1;0;;');
INSERT INTO @table_var VALUES ('146;0;3;this field');
SOL 1 :
SELECT DISTINCT S.a.value('(/H/r)[1]', 'VARCHAR(25)') AS col1
, S.a.value('(/H/r)[2]', 'VARCHAR(25)') AS col2
, S.a.value('(/H/r)[3]', 'VARCHAR(25)') AS col3
, S.a.value('(/H/r)[4]', 'VARCHAR(25)') AS col4
FROM
(
SELECT *,CAST (N'<H><r>' + REPLACE(col_list, ';', '</r><r>') + '</r></H>' AS XML) AS [vals]
FROM @table_var) d
CROSS APPLY d.[vals].nodes('/H/r') S(a)
Sol 2:
SELECT col_list,
NewXML.value('/col_list[1]/Attribute[1]', 'varchar(25)') AS [col1],
NewXML.value('/col_list[1]/Attribute[2]', 'varchar(25)') AS [col2],
NewXML.value('/col_list[1]/Attribute[3]', 'varchar(25)') AS [col3],
NewXML.value('/col_list[1]/Attribute[4]', 'varchar(25)') AS [col4]
FROM @table_var t1
CROSS APPLY (SELECT XMLEncoded=(SELECT col_list AS [*]
FROM @table_var t2
WHERE t1.col_list = t2.[col_list]
FOR XML PATH(''))) EncodeXML
CROSS APPLY (SELECT NewXML=Cast('<col_list><Attribute>'
+ Replace(XMLEncoded, ';', '</Attribute><Attribute>')
+ '</Attribute></col_list>' AS XML)) CastXML