我有一个表格如下
商业(BId - BName)
1 - ABC
2 - DEF
3 - GHI
4 - JKL
我创建了一个临时表
Create table #Temp(
TBID int,
TBNAME nvarchar(50)
);
现在我必须从像
这样的字符串中将数据添加到#temp中Declare string = 'ABC, GHI'
如何从上面的字符串中将数据添加到#temp表中,并在#temp
中添加相应的ID表#temp的输出应该像
#temp(TBID - TBNAME
1 - ABC
3 - GHI
答案 0 :(得分:2)
试试这个..你需要使用LTRIM and RTRIM
在转换成行后开始和结束时删除不需要的空间。
CREATE TABLE #Business
(BId INT,BName VARCHAR(50)
)
INSERT INTO #Business
VALUES (1,'ABC'),(2,'DEF'),(3,'GHI'),(4,'JKL')
DECLARE @strng VARCHAR(max) = 'ABC, GHI'
SELECT B.BId AS TBIB,
B.BName TBName
INTO #temp
FROM (SELECT Rtrim(Ltrim(Split.a.value('.', 'VARCHAR(100)'))) AS Data
FROM (SELECT Cast ('<M>' + Replace(@strng, ',', '</M><M>') + '</M>' AS XML) AS Data) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)) a
JOIN #Business B
ON a.data = B.BName
SELECT *
FROM #temp
答案 1 :(得分:1)
试试这个
DECLARE @S varchar(max),
@Split char(1),
@X xml
SELECT @S = 'ABC, GHI',
@Split = ','
SELECT @X = CONVERT(xml,' <root> <s>' +
REPLACE(@S,@Split,'</s> <s>') + '</s> </root> ')
SELECT [Value] = T.c.value('.','varchar(20)') into #tempTbl
FROM @X.nodes('/root/s') T(c)
select Bus.ID,tbl.Name from #tempTbl tbl JOIN Business Bus
on tbl.Value=Bus.BName
输出
ID Value
1 ABC
3 GHI