Sql server 2008 sql server案例
我想根据名为“type”的参数从不同的表中进行选择。我可以使用“CASE”从表中选择Sql server 2008 sql server案例,sql-server-2008,case,Sql Server 2008,Case,我想根据名为“type”的参数从不同的表中进行选择。我可以使用“CASE”从表中选择 我可以用这样的东西吗 select a as abc b as xyz from ( CASE when @type = 1 then tblSales when @type = 2 then tblTransfer end ) 我可能会这样做: SELECT a AS abc, b AS xyz FROM tblSales WHERE @type=1 UNION AL
我可以用这样的东西吗
select
a as abc
b as xyz
from ( CASE when @type = 1 then tblSales
when @type = 2 then tblTransfer
end
)
我可能会这样做:
SELECT a AS abc, b AS xyz FROM tblSales WHERE @type=1
UNION ALL
SELECT a AS abc, b AS xyz FROM tblTransfer WHERE @type=2
如果您想这样做,您可以尝试使用union(下面的示例),也可以使用简单的“if”语句
这里不能使用case语句,因为case返回的是单个值,而不是表(这是“from”所期望的)
这就是你要找的吗
select
a as abc,
b as xyz
from
tblSales
WHERE
@type = 1
UNION
select
a as abc,
b as xyz
FROM
tblTransfer
WHERE
@type = 2
这就是我将要做的——打败我!如果您发布代码、XML或数据示例,请在文本编辑器中突出显示这些行,并单击编辑器工具栏上的“代码示例”按钮({}
),以很好地格式化和语法突出显示它!谢谢;将来会这样做的!
create table #tblsales
(
a varchar(1),
b varchar(1)
)
create table #tblTransfer
(
a varchar(1),
b varchar(1)
)
insert into #tblSales(a,b) values ('s','1')
insert into #tblSales(a,b) values ('s','2')
insert into #tblTransfer(a,b) values ('t','1')
insert into #tblTransfer(a,b) values ('t','2')
declare @type int
set @type=1
select a as abc, b as xyz
from
(
select a,b,thetype
from
(select a,b, 1 as thetype from #tblsales) sales
union
(select a,b, 2 as theType from #tblTransfer)
) joined
where theType=@type
select
a as abc,
b as xyz
from
tblSales
WHERE
@type = 1
UNION
select
a as abc,
b as xyz
FROM
tblTransfer
WHERE
@type = 2