SQL Server存储过程创建具有动态列数的表
我是存储过程的新手,并试图弄清楚如何创建具有动态列数的表。
我正在使用 Microsoft SQL Server 2008。
我有以下查询,该查询旨在用于将从 XML 源传递的数据存储到应由该存储过程创建的表中。
CREATE PROCEDURE AddClaimData_newV2
@xml_text VARCHAR(4000),
@devYearColumnNumber INT
AS
DECLARE @i INT
DECLARE @tempTable TABLE (
ProductName VARCHAR(50),
Year INT,
Value1 FLOAT ,
Value2 FLOAT ,
Value3 FLOAT ,
Value4 FLOAT )
EXEC sp_xml_preparedocument @i OUTPUT, @xml_text
INSERT INTO @tempTable
SELECT * FROM
OPENXML(@i, '/root/Product/Year/Value1/Value2/Value3/Value4', 1)
WITH
(ProductName VARCHAR(50) '../../../../../@Name',
Year INT '../../../../@Year',
Value1 FLOAT '../../../@Value',
Value2 FLOAT '../../@Value',
Value3 FLOAT '../@Value',
Value4 FLOAT '@Value')
/* create a new table and store all the data from @tempTable */
EXEC sp_xml_removedocument @i
基本上,ProductName
和 Year
是固定列,但 Value[i]
列由参数 devYearColumnNumber
决定。
我的问题是:
- 如何使用参数动态创建这些
Value[i]
列 - ,然后如何使用这些列创建一个新表来存储来自
@tempTable
的数据
I'm new to stored procedure, and trying to figure out how to create a table with a dynamic number of columns.
I'm using Microsoft SQL Server 2008.
I have the following query which is meant to be used to store data passed from a XML source into a table which should be created by this stored procedure.
CREATE PROCEDURE AddClaimData_newV2
@xml_text VARCHAR(4000),
@devYearColumnNumber INT
AS
DECLARE @i INT
DECLARE @tempTable TABLE (
ProductName VARCHAR(50),
Year INT,
Value1 FLOAT ,
Value2 FLOAT ,
Value3 FLOAT ,
Value4 FLOAT )
EXEC sp_xml_preparedocument @i OUTPUT, @xml_text
INSERT INTO @tempTable
SELECT * FROM
OPENXML(@i, '/root/Product/Year/Value1/Value2/Value3/Value4', 1)
WITH
(ProductName VARCHAR(50) '../../../../../@Name',
Year INT '../../../../@Year',
Value1 FLOAT '../../../@Value',
Value2 FLOAT '../../@Value',
Value3 FLOAT '../@Value',
Value4 FLOAT '@Value')
/* create a new table and store all the data from @tempTable */
EXEC sp_xml_removedocument @i
Basically, ProductName
and Year
are fixed columns, but the Value[i]
columns are decided by parameter devYearColumnNumber
.
My questions are :
- how to use the parameter to dynamically create those
Value[i]
columns - then, how to create a new table with those columns to store data from
@tempTable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)