+ -
当前位置:首页 → 问答吧 → 不用union all使用变量表查询

不用union all使用变量表查询

时间:2011-11-10

来源:互联网

select userid from f201011 union all
select userid from f201012 union all
select userid from f201101 union all
select userid from f201102 union all
select userid from f201103 union all
select userid from f201104 union all
select userid from f201105 union all
select userid from f201106 union all
select userid from f201107 union all
select userid from f201108 union all
select userid from f201109 union all
select userid from f201110 
查询用户一年的信息,表每个月增加,该怎么做?

作者: liyingzi   发布时间: 2011-11-10

SQL code

CREATE PROCEDURE P1
(
@year nvarchar(4)
)
AS

DECLARE @s NVARCHAR(4000),@i INT
SELECT @i=1

WHILE @i<12
    SELECT @s=ISNULL(@s+' union all select ',' select ')+' userid from f'+@year+RIGHT(100+@i,2),@i=@i+1
EXEC(@s)

作者: roy_88   发布时间: 2011-11-10

本年度f201111\f201112还没生成呢要查去年的f201011\f201012,下面变量表这段应该没错

作者: liyingzi   发布时间: 2011-11-10

动态 SQL?

作者: fredrickhu   发布时间: 2011-11-10

思路给你了,自己改一下初始值不会?
引用 2 楼 liyingzi 的回复:

本年度f201111\f201112还没生成呢要查去年的f201011\f201012,下面变量表这段应该没错

作者: geniuswjt   发布时间: 2011-11-10

确实不会,请指教,原来这个应该叫动态SQL,难道就这么沉了,自己顶一下

作者: liyingzi   发布时间: 2011-11-10

引用 5 楼 liyingzi 的回复:

确实不会,请指教,原来这个应该叫动态SQL,难道就这么沉了,自己顶一下

参数1楼方法
在显示生成语句用 EXEC(@s) 改为 print @s
可以看到生成格式

作者: roy_88   发布时间: 2011-11-10

SQL code
CREATE PROCEDURE P1
(
@year nvarchar(4)
)
AS

DECLARE @s NVARCHAR(4000),@i INT,@j int
SELECT @i=1,@j=12
if YEAR(GETDATE())=@year
    set @j=MONTH(GETDATE())

WHILE @i<@j
    SELECT @s=ISNULL(@s+' union all select ',' select ')+' userid from f'+@year+RIGHT(100+@i,2),@i=@i+1

EXEC(@s)

作者: roy_88   发布时间: 2011-11-10

热门下载

更多