实现如下需求
如果table1的col1字段 值为 1,从test1表中取数据
如果table1的col1字段 值为 2,从test2表中取数据
create table test1
(
col int
);
insert test1 (col) values(10);
create table test2
(
col int
);
insert test2 (col) values(20);create table table1
(
col1 int,
col2 int,
col3 int,
col int
);
insert table1 (col1) values(1);--如果table1的col1字段 值为 1,从test1表中取数据
--如果table1的col1字段 值为 2,从test2表中取数据
declare @tempid int
select @tempid = col1
from table1
-- 下面代码无法使用
-- select * from (case when @tempid = 1 then test1 else test2 end)
如果table1的col1字段 值为 1,从test1表中取数据
如果table1的col1字段 值为 2,从test2表中取数据
create table test1
(
col int
);
insert test1 (col) values(10);
create table test2
(
col int
);
insert test2 (col) values(20);create table table1
(
col1 int,
col2 int,
col3 int,
col int
);
insert table1 (col1) values(1);--如果table1的col1字段 值为 1,从test1表中取数据
--如果table1的col1字段 值为 2,从test2表中取数据
declare @tempid int
select @tempid = col1
from table1
-- 下面代码无法使用
-- select * from (case when @tempid = 1 then test1 else test2 end)
解决方案 »
- 怎么把ppt文件存入数据库中
- 我的 VS 2010 怎么没有安装部署项目 模板?
- Sql Update
- update 里面需要用到 avg()函数, sql提示不能用,有什么好办法么?
- 我要建一个表,有一列是时间,该时间要求精确到“年-月-日 小时-分-秒”,怎么办???
- 重复插入表中已有的记录,但是序号字段值改成其他值,重量值改成负数
- 关于sql 存储和读取 xml字段的问题
- SQL2000的表里一列 数据类型是varchar(40)能存下DataLength 是 41 的字符么?
- 新手入门,请多关照!高手们,指点几招吧!
- [50分]如何把EXCEL文件导入远程数据库作为一个新表
- 条件的顺序会影响性能吗?
- sqlite 多表连接插入数据
create table table1
( col1 int,col2 int,col3 int,col int)insert table1(col1) values(1)
-- 方法1
declare @tempid int,@tsql varchar(6000)select @tempid=col1 from table1
select @tsql='select * from '+case @tempid when 1 then 'test1' when 2 then 'test2' endexec(@tsql)-- 方法2
declare @tempid intselect @tempid=col1 from table1if @tempid=1
select * from test1
else
select * from test2
-- 结果
/*
col
-----------
10(1 row(s) affected)
*/
select * from test1 where @tempid = 1
union all
select * from test2 where @tempid = 2
if @tempid=1
select * from test1
else
select * from test2