我有一个具有以下结构的查询:
DECLARE @VARIABLE as varchar(30)
SET @VARIABLE = 'Thing to look up'
select * from ref.Table1 where columnX = @VARIABLE
select * from ref.Table2 where columnX2 = @VARIABLE
...
select * from ref.TableN where columnXn = @VARIABLE
我使用检查许多具有不同列的参考表,但使用我在@VARIABLE中寻找的相同标识符。
我正在检查50多张桌子。 我只想在特定表格中与@VARIABLE匹配时返回结果。
我不是开发人员,但我确定有一个更多的程序设计'这样做的方式。什么是更推荐的方式?
编辑:
要清楚,我当前的查询在SQL Server 2012 UI中工作,我在那里进行日常工作。我运行查询,我得到大约50个表返回。大多数没有匹配,所以我只看到标题。我想只返回有匹配的表格。
答案 0 :(得分:1)
好吧,好像这是一个特殊的查询,你可以在查询分析器或visual studio这样的前端运行。
你可以使用if语句,如果存在,就像这样:
IF EXISTS(select * from ref.Table1 where columnX = @VARIABLE)
select * from ref.Table1 where columnX = @VARIABLE
;
要仅运行一次查询以加快速度,请执行以下操作:
select * from ref.Table1 INTO #mytmp1 where columnX = @VARIABLE
IF EXISTS(SELECT * FROM #mytmp1)
SELECT * FROM #mytmp1
;
正如@LaughingVergil所指出的那样,如果你的id不在第一个表中就可以解决问题,你可以这样解决:
select Table1.*, Table2.*, Table3.*, TableN.*
from (
SELECT @VARIABLE as Criteria
) base
left join ref.Table1 where columnX = base.Criteria
left join ref.Table2 where columnX2 = base.Criteria
left join ref.Table3 where columnX3 = base.Criteria
-- ...
left join ref.TableN where columnXN = base.Criteria
to"辨别"什么表数据来自
select
Table1.Field1 as Table1.Field1, Table1.Field2 as Table1.Field2, -- etc
Table2.Field1 as Table2.Field1, Table2.Field2 as Table2.Field2, -- etc
Table3.Field1 as Table3.Field1, Table3.Field2 as Table3.Field2, -- etc
TableN.Field1 as TableN.Field1, TableN.Field2 as TableN.Field2 -- etc
from (
SELECT @VARIABLE as Criteria
) base
left join ref.Table1 where columnX = base.Criteria
left join ref.Table2 where columnX2 = base.Criteria
left join ref.Table3 where columnX3 = base.Criteria
-- ...
left join ref.TableN where columnXN = base.Criteria
原始回答
通常在SQL中我们使用JOIN来处理这种情况(除非您不关心具有相同名称的多个列,否则您可能需要更具体地了解列)
DECLARE @VARIABLE as varchar(30)
SET @VARIABLE = 'Thing to look up'
select Table1.*, Table2.*, Table3.*, TableN.*
from ref.Table1
left join ref.Table2 where columnX2 = columnX
left join ref.Table3 where columnX3 = columnX
-- ...
left join ref.TableN where columnXN = columnX
where columnX = @VARIABLE
通常使用视图使其更容易(此处您必须具体说明列名称,否则创建视图将失败)。
create view myview as
select Table1.*, Table2.*, Table3.*, TableN.*
from ref.Table1
left join ref.Table2 where columnX2 = columnX
left join ref.Table3 where columnX3 = columnX
-- ...
left join ref.TableN where columnXN = columnX
然后
select *
from myview
where columnX = @VARIABLE
答案 1 :(得分:0)
您的基本查询表格应为 - 如果您希望表格参考:
SELECT 'Table1', * FROM Table1 WHERE columnx = @VARIABLE
UNION
SELECT 'Table2', * FROM Table2 WHERE columnx2 = @VARIABLE
UNION ...
SELECT 'TableN', * FROM TableN WHERE columnxN = @VARIABLE
如果您想知道它是否存在于任何表中:
SELECT * FROM Table1 WHERE columnX = @VARIABLE
UNION
SELECT * FROM Table2 WHERE columnX2 = @VARIABLE
UNION ...
SELECT * FROM TableN WHERE columnXN = @VARIABLE
注意:UNION
将重复删除行。如果您想要包含重复的行,请将UNION
更改为UNION ALL