我正在尝试从表(dbo.Ordinal)中动态选择我的列,该表列出了每一列及其位置。这些列标题对应于表Y2。
DECLARE
@ord int = 1,
@colname varchar(max),
@div varchar(max) = '',
@sql varchar (max)
WHILE @ord < 3 BEGIN
SET @ord = @ord + 1
Set @colname = '(SELECT BR FROM dbo.[Ordinal] WHERE ORDINAL_POSITION=' +CAST(@ord AS Varchar(10))+')'
SET @div = @div + ',' +(@colname)
END
Set @sql = '(SELECT Simulation' + @div + ' FROM dbo.[Y2 HR]) ORDER BY Simulation'
EXECUTE (@sql)
此代码当前使用我尝试选择的列标题填充结果表。理想情况下,我希望看到@div生成一个文本字符串opf所需的列,然后可以在@sql中使用,
目前,如果我打印@sql,输出为:
(SELECT Simulation,(SELECT BR FROM dbo.[Ordinal] WHERE ORDINAL_POSITION=2),(SELECT BR FROM dbo.[Ordinal] WHERE ORDINAL_POSITION=3) FROM dbo.[Y2 HR]) ORDER BY Simulation.
欢迎以任何方式实现这一目标或建议不同的方法
由于
答案 0 :(得分:2)
你可以做得更简单:
DECLARE
@ord int = 1,
@colname varchar(max),
@div varchar(max) = '',
@sql varchar (max)
WHILE @ord < 3 BEGIN
SET @ord = @ord + 1
SELECT @colname = BR FROM dbo.[Ordinal] WHERE ORDINAL_POSITION= @ord
SET @div = @div + ',' +(@colname)
END
Set @sql = '(SELECT Simulation' + @div + ' FROM dbo.[Y2 HR]) ORDER BY Simulation'
EXECUTE (@sql)