0

我们收到的数据格式如下:

'1:0,2:1,3:1,4:0'

值用逗号分隔:冒号前的值为 studentId,冒号后为位值。

我想将这些值存储在临时表中:

studentID   |   BitValue
1           |    0
2           |    1
3           |    1
4           |    0

如何在 SQL Server 2005 中执行此操作?

4

2 回答 2

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
于 2013-04-19T11:56:59.027 回答
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
于 2013-04-19T12:09:41.610 回答