常用sql備忘

2021-10-06 09:00:49 字數 3643 閱讀 6400

簡單的while迴圈比使用游標快很多,原因應該是不需要 fetch 顯示資料,還有不需要將資料select出來存到游標中

select * from users 

declare @i int

set @i = (select count(*) from users where employeeid is null)

while @i > 0

begin

declare @userid varchar(100)

set @userid = (select top 1 userid from users where employeeid is null)

update users set employeeid = 1 where userid = @userid

set @i = @i - 1

enddeclare my_cursor cursor --定義游標

for (select * from users) --查出需要的集合放到游標中

open my_cursor; --開啟游標

fetch next from my_cursor ; --讀取第一行資料

while @@fetch_status = 0

begin

update users set employeeid = 0 where current of my_cursor; --更新

--delete from dbo.memberaccount where current of my_cursor; --刪除

fetch next from my_cursor; --讀取下一行資料

endclose my_cursor; --關閉游標

deallocate my_cursor; --釋放游標

go

還可以迴圈字串

比如字串內以「,」分隔

from laborhour where ([year] = @year or @year = '' or @year = '請選擇...' ) and usertype != @type and usertype <> @type and delflag = 0

group by usercode,username,project

select * ,m01 + m02 + m03 + m04 + m05 + m06 + m07 + m08 + m09 + m10 + m11 + m12 as total into #2 from #1

drop table #1

if @pageno = 0 and @pagesize = 0

select 使用者編碼 = usercode,使用者名稱 = username,專案名稱=project, 一月 = m01,二月 = m02,三月 = m03,四月 = m04,五月 = m05,六月 = m06,七月 = m07,八月 = m08,九月 = m09,十月 = m10,十一月 = m11,十二月 = m12,合計 = total

from #2 order by usercode

else

select * from (select row_number()over(order by usercode desc)rownumber,* from #2)a where rownumber > @num and rownumber <= (@num + @pagesize)

select count(*) from #2

drop table #2

end

SQL語句備忘

rank 排序 每個分組進行單獨排名,相同名次的會佔位,比如兩個第二名,就沒有第三名了,直接到第四名 select fenxiaoid,price,rank over 使用rank 進行排名 partition by fenxiaoid 使用fenxiaoid進行分組 order by price ...

sql知識備忘

1 全部刪除表中資料 trancate update 2 將乙個表中的資料全部備份到備份表中 insert into 備份表名 select from 原始表名 3 刪除表中關於某乙個欄位的重複資料 delete from 表 where rowid in select rid from selec...

sql語句備忘

1.對一張表分類查詢,同時還需要另一張表的字段 select a.kindid,a.scoreall,b.kindname from select kindid,cast cast sum abs score as decimal 100 as decimal 18,2 as scoreall fr...