代码改变世界

動態修改 XML 欄位

2016-06-24 21:25  Koy  阅读(...)  评论(...编辑  收藏

/* -- for test
DECLARE @content VARCHAR(50)
DECLARE @folioId VARCHAR(50)
DECLARE @opinionType VARCHAR(50)
SET @content = 'this is board'
SET @folioId = '4BC3141E-BEF5-4528-8B0B-600B7987246D'
SET @opinionType = 'opinion_board'
*/

IF(EXISTS(SELECT opinion FROM folio WHERE folio_id = @folioId AND opinion IS null)) BEGIN
UPDATE folio SET opinion = '<opinion></opinion>' WHERE folio_id = @folioId
END

DECLARE @val VARCHAR(50)
SELECT @val = opinion.value('(/opinion/*[local-name()=sql:variable(''@opinionType'')])[1]', 'nvarchar(max)' ) FROM folio WHERE folio_id = @folioId
if @val IS NOT NULL BEGIN
IF @val = '' BEGIN
UPDATE folio SET opinion.modify('insert text{sql:variable(''@content'')} into (/opinion/*[local-name()=sql:variable(''@opinionType'')])[1]')
WHERE folio_id = @folioId
END ELSE BEGIN
UPDATE folio SET opinion.modify('replace value of (/opinion/*[local-name()=sql:variable(''@opinionType'')]/text())[1] with sql:variable(''@content'')')
WHERE folio_id = @folioId
END
END
ELSE BEGIN
UPDATE folio SET opinion.modify('insert
if(sql:variable(''@opinionType'') = ''opinion_edit'')
then element opinion_edit { sql:variable(''@content'') }
else if(sql:variable(''@opinionType'') = ''opinion_dept'')
then element opinion_dept { sql:variable(''@content'') }
else if(sql:variable(''@opinionType'') = ''opinion_board'')
then element opinion_board {sql:variable(''@content'')}
else ()
into (/opinion)[1]')
WHERE folio_id = @folioId
END