如何基于主键Sql Server将XML数据更新到表中

时间:2015-09-28 07:57:51

标签: sql sql-server xml

我有这样的XML字符串:

LanguageId int 
Language Varchar(50)
UserID INT

$sql5="update sms set sms='$remaining_sms' WHERE username='$session_username'";
$result5=mysql_query($sql5);

1 个答案:

答案 0 :(得分:1)

假设你在一个名为@input的SQL变量中使用了这个XML(假设你已经将“语言”修复为整个XML的“语言”正确拼写)那么你可以使用这样的东西来提取信息:

;WITH XmlData AS
(
    SELECT
        UserId = XC.value('(UserID)[1]', 'int'),
        LanguageId = XC.value('(LanguageId)[1]', 'int'),
        [Language] = XC.value('(Language)[1]', 'varchar(50)')
    FROM
        @input.nodes('/ArrayOfSpokenLanguageInfo/SpokenLanguageInfo') AS XT(XC)
)
SELECT *
FROM XmlData

这会为您提供如下输出:

enter image description here

更新:如果您只想插入新项目而只插入有UserId的项目,您可以使用以下内容:

;WITH XmlData AS
(
    SELECT
        UserId = XC.value('(UserID)[1]', 'int'),
        LanguageId = XC.value('(LanguageId)[1]', 'int'),
        [Language] = XC.value('(Language)[1]', 'varchar(50)')
    FROM
        @input.nodes('/ArrayOfSpokenLanguageInfo/SpokenLanguageInfo') AS XT(XC)
)
INSERT INTO dbo.YourTable(UserId, LanguageId, [Language])
   SELECT    
      x.UserId, x.LanguageId, x.[Language]
   FROM 
      XmlData x
   WHERE
      x.UserId IS NOT NULL
      AND NOT EXISTS (SELECT * FROM dbo.YourTable tbl
                      WHERE tbl.UserId = x.UserId)