我有一个XML变量,如下所示:
<code>
<IDs>
<ID id="1">a</ID>
<ID id="43">d</ID>
<ID id="3">b</ID>
</IDs>
</code>
我想在将更新表的存储过程(SQL Server)中使用它。
我的表格如下:
ID INT,
a INT,
b INT,
c INT,
d INT
该语句应增加与id相关联的字母值。
所以看起来像这样:
Table Row with ID = 1, update column "a" by increasing the current value by 1.
Table Row with ID = 43 - update column "d" by increasing current value by 1.
Finally Table row with ID= 3 - update column "b" by increasing value by 1.
这就是我到目前为止 - (第二行是我需要最多帮助的地方。):
Update MyTable
SET @letter = letterVal +1
WHERE ID IN(
SELECT x.v.value('@id','INT')
FROM @xmlIDs.nodes('/IDs/ID') x(v)
)
答案 0 :(得分:2)
你必须按照以下方式做点什么:
DECLARE @input XML = '<code>
<IDs>
<ID id="1">a</ID>
<ID id="43">d</ID>
<ID id="3">b</ID>
</IDs>
</code>'
;WITH ParsedXML AS
(
SELECT
ID = C.value('(@id)[1]', 'int'),
ColumnName = C.value('(.)[1]', 'varchar(10)')
FROM @Input.nodes('/code/IDs/ID') AS T(C)
)
UPDATE MyTable
SET a = CASE WHEN p.ColumnName = 'a' THEN t.a + 1 ELSE t.a END,
b = CASE WHEN p.ColumnName = 'b' THEN t.b + 1 ELSE t.b END,
c = CASE WHEN p.ColumnName = 'c' THEN t.c + 1 ELSE t.c END,
d = CASE WHEN p.ColumnName = 'd' THEN t.d + 1 ELSE t.d END
FROM MyTable t
INNER JOIN ParsedXml p ON t.ID = p.ID
SELECT * FROM Mytable
这样做会 - 但它真的很难看。主要问题是:你不能从其他地方获取列名作为值,在UPDATE
语句中使用它 - 除非你去动态SQL路由,它有自己的优点和缺点,可以得到相当混乱。
如果您对动态SQL感兴趣 - Erland Sommarskog的The Curse and Blessings of Dynamic SQL是绝对必读 - 在之前阅读,您开始使用动态SQL !
答案 1 :(得分:0)
我建议您将XML更改为类似于:
<questions>
<question id="1" answer="a" />
<question id="43" answer="d" />
<question id="3" answer="b" />
</questions>
使用此格式,您可以编写如下查询:
with CTE as (
select
x.n.value('@answer', 'char(1)') as answer
from
@Input.nodes('//questions/question') as x(n)
)
select
answer,
count(answer) as answerCount
from
CTE
group by
answer;
然后,您可以根据需要将这些添加到表中,但您设计的表看起来不太有用。
答案 2 :(得分:0)
一种动态SQL解决方案。不太漂亮,但完全充满活力:
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp
GO
CREATE TABLE #tmp ( ID INT, a INT, b INT, c INT, d INT )
GO
INSERT INTO #tmp VALUES
( 1, 0, NULL, NULL, NULL ),
( 43, NULL, NULL, NULL, 0 ),
( 3, NULL, 0, NULL, NULL )
GO
SELECT 'before' s, * FROM #tmp
DECLARE @xml XML
SET @xml = '<code>
<IDs>
<ID id="1">a</ID>
<ID id="43">d</ID>
<ID id="3">b</ID>
</IDs>
</code>'
-- Run a cursor through the XML resultset to update the table
DECLARE update_cursor CURSOR FAST_FORWARD LOCAL FOR
SELECT
x.y.value('@id', 'INT') id,
x.y.value('.', 'VARCHAR(50)') columnName
FROM @xml.nodes('code/IDs/ID') AS x(y)
-- Cursor variables
DECLARE @id INT, @columnName VARCHAR(50)
DECLARE @sql NVARCHAR(MAX)
OPEN update_cursor
FETCH NEXT FROM update_cursor INTO @id, @columnName
WHILE @@fetch_status = 0
BEGIN
--SELECT @id, @columnName
SET @sql = 'UPDATE #tmp SET ' + @columnName + ' += 1 WHERE ID = ' + CAST( @id AS VARCHAR(20) )
EXEC(@sql)
--SELECT @sql
FETCH NEXT FROM update_cursor INTO @id, @columnName
END
CLOSE update_cursor
DEALLOCATE update_cursor
GO
SELECT 'after' s, * FROM #tmp