我是存储过程的新手,并试图找出如何使用动态列数创建表。
我正在使用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
答案 0 :(得分:1)
declare @currentColumnNumber int, @sqlCommandToCreateTable nvarchar(4000)
set @currentColumnNumber = 1
set @sqlCommandToCreateTable = 'CREATE TABLE testClaimData (
ProductName VARCHAR(50),
Year INT '
while @currentColumnNumber <= @devYearColumnNumber
begin
set @sqlCommandToCreateTable = @sqlCommandToCreateTable + ' ,
Value' + convert(varchar, @currentColumnNumber) + ' FLOAT'
set @currentColumnNumber = @currentColumnNumber + 1
end
set @sqlCommandToCreateTable = @sqlCommandToCreateTable + ' )'
exec sp_executeSql @sqlCommandToCreateTable
--[Test this with:]-- exec sp_executeSql N'select * from testClaimData'
--similar mechanism for the "INSERT INTO" here