从多个表中选择(通过另一个选择传递)

时间:2019-02-11 14:56:53

标签: sql sql-server sql-server-2014 dynamic-sql

问题已更新。

我要实现的是在options字段中获取新表的列表,这些表是@font-face { font-family: Gotham; src: url("Gotham-Book.otf") format("opentype"); } body{ font-size: 3rem; font-family: Gotham; } empty。 (新表表示前缀为new_),并且所有表都有描述字段。

表定义:

null

样本数据和描述:

description

就像您在我的示例中注意到的那样,示例数据的理想输出应该是:

create table topic (id int, description varchar(255));
create table comment (id int, description varchar(255));
create table author (id int, description varchar(255));
create table new_topic (id int, description varchar(255));
create table new_comment (id int, description varchar(255));
create table new_author (id int, description varchar(255));

我的实际解决方案有效,但是我需要手动添加表,并且需要重复很多次。

insert into new_topic (id, description) values (1, null);
insert into new_topic (id, description) values (2, 'This is topic description');
insert into new_comment (id, description) values (1, null);
insert into new_comment (id, description) values (2, null);
insert into new_author (id, description) values (1, 'This is casual first author.');
insert into new_author (id, description) values (2, 'This is casual second author.');

我的解决方案的输出如下:

table_name:
new_topic
new_comment

我还创建了SELECT来获取所有新表:

select  distinct 'new_topic' as table_name
from new_topic where description is null
select distinct 'new_comment' as table_name
from new_comment where description is null
select  distinct 'new_author' as table_name
from new_author where description is null

这可能是我先前选择的入口,但是我不知道如何将这两者连接起来。

我的解决方案也可以在dbfiddle上获得

2 个答案:

答案 0 :(得分:1)

哦,我想我明白你的追求。是的,这需要动态SQL。另外,请注意,查询查找所有名称类似于new_的表的方法不太正确。下划线是通配符模式检查。这样,当您不想使用该表时,它将返回一个名为“ news”的表。将下划线放在方括号中即可解决此问题。这是我将如何处理这种类型的查询。代码中的注释应对此进行解释。

declare @SQL nvarchar(max) = '' --this must be initialized to an empty string for this to work.

select @SQL = @SQL + 'select distinct TableName = ''' + t.name + ''' from ' + quotename(t.name) + ' where description is null union all '
from sys.tables t
where name like 'new[_]%' --need the square brackets because the underscore is a wildcard so you might get false positives


select @SQL = left(@SQL, len(@SQL) - 10)

--this will show you the dynamic sql
select @SQL

--once you are satisfied the dynamic sql is correct uncomment the next line to execute it
--exec sp_executesql @SQL

答案 1 :(得分:-1)

您能不能做:-

select table_name from information_schema.columns 
where table_name like 'prefix_%' and (column_name is null or column_name='')