動態SQL應用小列子

2021-09-23 21:10:54 字數 1546 閱讀 9123

呵呵,幾乎成標題黨了,今天要寫個指令碼查詢7天內所有有登入玩家的資料,要求按註冊日期統計,雖然是個簡單的問題,但是關鍵是使用者表有30個,分別是 user0, user1......到user29 ,光是把它們union all起來,我都夠鬱悶了,你想象下指令碼有多長吧,一大堆堆在那兒,光是複製都讓你難以忍受。 

code highlighting produced by actipro codehighlighter (freeware)>select id,convert(varchar(10),create_time, 120), last_login_time from user0

union all

select id,convert(varchar(10),create_time, 120), last_login_time from user1

union all

select id,convert(varchar(10),create_time, 120), last_login_time from user2

.........

呵呵,下面是我用動態sql 改寫的,呵呵,簡潔多了

code highlighting produced by actipro codehighlighter (freeware)>declare @cmdtext varchar(8000);

declare @userindex int;

set @cmdtext = '';

set @userindex = 0;

while @userindex <30

begin

if (@userindex != 29)

select @cmdtext = @cmdtext + 'select id,create_time, last_login_time from '

+ ' dbo.user' + convert(varchar,@userindex)

+ ' union all' + char(10); --換行

else

select @cmdtext = @cmdtext + 'select id,create_time, last_login_time from '

+ 'dbo.user' + convert(varchar,@userindex) ;

set @userindex = @userindex + 1;

end;

select @cmdtext = 'select convert(varchar(10),t.create_time, 120) as create_time ,count(0) as recordnum from ('

+ @cmdtext +

') t where datediff(d,last_login_time,getdate()) < 7 group by convert(varchar(10),create_time, 120) ';

--print @cmdtext

exec (@cmdtext);

這裡得提提

動態SQL應用小列子

呵呵,幾乎成標題黨了,今天要寫個指令碼查詢7天內所有有登入玩家的資料,要求按註冊日期統計,雖然是個簡單的問題,但是關鍵是使用者表有30個,分別是user0,user1.到user29 光是把它們union all起來,我都夠鬱悶了,你想象下指令碼有多長吧,一大堆堆在那兒,光是複製都讓你難以忍受。se...

七 SQL 子查詢 列子查詢

與標量子查詢不同,列值子查詢可以返回乙個多行多列的結果集。這樣的子查詢又被稱為錶子查詢,錶子查詢可以看作乙個臨時的表,錶子查詢可以用在select 語句的from子句中 insert語句 連線 in 子句等很多場合。首先來看乙個在from子句中使用的最簡單的錶子查詢。sql語句如下 select t...

mybatis 動態sql 應用舉例

基本應用 select from blog where state active and title like 使用if select from blog where state active and title like and author name like 使用choose select f...