我们收到的数据格式如下:
'1:0,2:1,3:1,4:0'
值以逗号分隔:冒号前面的值是studentId,后面是位值。
我想将这些值存储在临时表中:
studentID | BitValue
1 | 0
2 | 1
3 | 1
4 | 0
如何在SQL Server 2005中执行此操作?
答案 0 :(得分:2)
这适用于 MS SQL Server 2008 。
IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL
drop table #TempTable
create table #TempTable (studentID int, BitValue int)
declare @var nvarchar(max)
set @var='1:0,2:1,3:1,4:0'
set @var='insert into #TempTable values ('+REPLACE(REPLACE(@var,',','),('), ':', ',')+')'
exec (@var)
select * from #TempTable
drop table #TempTable
MS SQL Server 2005 ,请尝试:
IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL
drop table #TempTable
create table #TempTable (studentID int, BitValue int)
declare @var nvarchar(max)
set @var='1:0,2:1,3:1,4:0'
--set @var=REPLACE(@var,',','),(')
set @var='insert into #TempTable values ('+REPLACE(REPLACE(@var,',','); insert into #TempTable values('), ':', ',')+')'
exec (@var)
select * from #TempTable
drop table #TempTable
答案 1 :(得分:1)
试试这个
DECLARE @param NVARCHAR(MAX)
SET @param = '1:0,2:1,3:1,4:0'
;WITH Split_Col
AS
(
SELECT CONVERT(XML,'<table><col>' + REPLACE(ColName,':', '</col><col>') + '</col></table>') AS xmlcol
FROM
(
SELECT Split.a.value('.', 'VARCHAR(100)') AS ColName
FROM
(
SELECT CAST ('<M>' + REPLACE(ColName, ',', '</M><M>') + '</M>' AS XML) AS ColName
FROM (SELECT @param AS ColName) TableName
) AS A CROSS APPLY ColName.nodes ('/M') AS Split(a)
) TableName
)
SELECT
xmlcol.value('/table[1]/col[1]','varchar(100)') AS studentID,
xmlcol.value('/table[1]/col[2]','varchar(100)') AS BitValue
FROM Split_Col
修改强>
假设您的学生表有列StudentId,Name。找到加入学生表的更新查询
SELECT ST.Name,SP.studentID,SP.BitValue FROM
(
SELECT
xmlcol.value('/table[1]/col[1]','varchar(100)') AS studentID,
xmlcol.value('/table[1]/col[2]','varchar(100)') AS BitValue
FROM Split_Col
) SP
INNER JOIN Student ST on SP.studentID = ST.studentID