最好的方法,T-SQL中的Dynamic OpenXML

时间:2010-01-11 02:05:56

标签: sql tsql openxml

我将XML值存储到我的数据库中的条目。最初,我将xml数据类型提取到我的业务逻辑,然后将XML数据填充到DataSet中。我想通过将XML加载到T-SQL中来改进此过程。而不是将xml作为字符串,然后在BL上转换它。

我的问题是:每个xml条目都是动态的,这意味着它可以是用户创建的任何列。我尝试使用这种方法,但它给了我一个错误:

    CREATE PROCEDURE spXMLtoDataSet
    @id uniqueidentifier,
    @columns varchar(max)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @name varchar(300);
    DECLARE @i int;
    DECLARE @xmlData xml;
    (SELECT @xmlData = data, @name = name FROM XmlTABLES WHERE (tableID = ISNULL(@id, tableID)));

    EXEC sp_xml_preparedocument @i OUTPUT, @xmlData

    DECLARE @tag varchar(1000);
    SET @tag = '/NewDataSet/' + @name;
    DECLARE @statement varchar(max)
    SET @statement = 'SELECT * FROM OpenXML(@i, @tag, 2) WITH (' + @columns + ')';
    EXEC (@statement);

    EXEC sp_xml_removedocument @i
END

我传递动态写的@columns。

例如:

spXMLtoDataSet 'bda32dd7-0439-4f97-bc96-50cdacbb1518', 'ID int, TypeOfAccident int, Major bit, Number_of_Persons int, Notes varchar(max)'

但它一直在抛弃这个例外:

Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@i".
Msg 319, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon.

2 个答案:

答案 0 :(得分:1)

用此

替换您的@statement
SET @statement = 'DECLARE @i int;
DECLARE @xmlData xml;
(SELECT @xmlData = data, @name = name FROM XmlTABLES WHERE (tableID = ISNULL(@id, tableID)));
EXEC sp_xml_preparedocument @i OUTPUT, @xmlData
SELECT * FROM OpenXML(@i, @tag, 2) WITH (' + @columns + ')';
EXEC (@statement);

答案 1 :(得分:0)

您对sp_xml_%(两者)的调用也必须是动态的,因此可以识别句柄@i

当然,这在您的客户端代码中最好吗?

关闭主题:以及GUID PK吗?