我需要从表中选择表名后缀来自另一个表,如下所示:
declare @value nvarchar(3),
@table nvarchar(1000),
@SQLST NVARCHAR(255);
set @value = N'select column1 from tableX';
EXEC @value
set @table ='partoftableY'
Set @SQLST ='select * from' +@tabel + @value -- here I create the table name
但是TableX(0-999)中有多个值,所以这不起作用。我是否需要For Each类型构造。
答案 0 :(得分:1)
这里是我用两个表(partoftableY1和ampoftableY2)创建的示例,每个表中包含不同的数据
/*
create table tableX (column1 int);
insert into tablex
select 1
union all select 2;
create table partoftableY1 (data nvarchar(50));
create table partoftableY2 (data nvarchar(50));
insert into partoftableY1 select 'hey 1 here';
insert into partoftableY2 select 'hey 2 here';
*/
declare @sql nvarchar(max)
-- use the ability of SQL to build up string of all the sql you need to run
set @sql = 'select data from (select '''' as data'
select @sql = COALESCE(@sql + ' union all ', '')
+ 'select data from partoftableY'
+ cast(column1 as nvarchar(4)) from tableX
select @sql = @sql + ') X where data <>'''''
-- DEBUG for seeing what SQL you created
print @sql
-- Now execute the SQL
exec sp_executesql @sql= @sql
给了我
的结果hey 1 here
hey 2 here
您需要针对数据类型调整它,但这应该为您提供主要想法
这里的参考是创建和执行的sql:
select data
from (
select '' as data
union all select data from partoftableY1
union all select data from partoftableY2
) X
where data <>''
N.B。
答案 1 :(得分:0)
你可以试试这个
DECLARE @SQLST NVARCHAR(max)='';
DECLARE @select nvarchar(max)=N'select * from partoftableY'
DECLARE @union nvarchar(max)=N'
UNION ALL
'
SELECT @SQLST=@select+column1+@union
FROM tablex
SELECT @SQLST=substring(@SQLST,1,LEN(@SQLST)-11)
EXEC sp_executesql @SQLST