sql 語句拼接 游標遍歷和函式遍歷

2021-07-27 21:54:24 字數 1806 閱讀 3290

--對於表的遍歷在很多時候都要用到, 下面給出了兩種方法

declare @table table(code int,msg nvarchar(15));--宣告表作為遍歷物件

declare @code varchar(15); declare @msg varchar(20);

declare @i int ;set @i=1;

while (@i<100000)--得到表的總行數

begin

insert into @table(code,msg) values(@i,'我是'+cast(@i as char(6)))

set @i=@i+1;

end

--使用游標遍歷表

declare @curl cursor;

set @curl =cursor forward_only static for

select code ,msg from @table;

open @curl--開啟游標

fetch next from @curl into @code,@msg;

while(@@fetch_status=0)

begin

print @code;

fetch next from @curl into @code,@msg;

end

close @curl;--關閉游標

deallocate @curl;--刪除游標

--使用函式遍歷

while exists(select top 1 code from @table)

begin

select top 1 @code=code,@msg=msg from @table

print @code;

delete from @table where code=@code

end--在實際中據說函式的遍歷比游標要快,而且記憶體占用較少.但是自己沒有接觸過大資料,所以在實際中怎麼樣也不得而知.

--在本例中 由於函式要查詢和刪除 游標速度較快

/*sql 語句拼接*/ --200個0-10的隨機數 拿隨機數和7相處,如果餘數是0 c0的值+1,最後得到200個數字出去7餘數是幾的和 create table test (stat char(1), --在拼接的時候 對於如何使用臨時表 還是不會 所以在這裡建立表 c0 int, c1 int, c2 int, c3 int, c4 int, c5 int, c6 int, num varchar(500)); insert into test values('n',0,0,0,0,0,0,0,''); declare @i int; set @i =0; declare @remainder int ; declare @num int ; declare @sql nvarchar(100)--注意一定要是nvarchar while(@i<200) begin set @num=(cast ( rand ()*10 as int )); set @remainder=@num%7; set @sql=n'update test set c'+cast(@remainder as char (1))+' =c'+cast(@remainder as char (1))+'+1,num=num+'''+cast (@num as char(1))+''' where stat=''n''';--n'string' 表示string是個unicode字串 print @sql; exec sp_executesql @sql set @i=@i+1; end select * from test

PHP函式 sprintf 拼接sql語句

簡單常用的有 u 和 s,其中 u 是自然整數 包括0,1,2.例如有一條 select from users where user id in 1,2,3,6,7 而我們接受到的引數是乙個 陣列 1,2,3,6,7 我們可以這樣寫sql userids 1,2,3,6,7 sql sprintf ...

不用游標 遍歷記錄的sql語句

宣告變數表 tb declare tbtable id int,name varchar 50 新增測試資料 insert into tbselect6,aa union allselect7,bb union allselect8,cc union allselect9,dd union alls...

JDBC操作SQL語句的注釋和拼接

上網瀏覽帖子發現乙個關於sql中的in裡面的引數動態新增的問題。通常in裡面的引數通過乙個子查詢獲得與該引數相同型別或者可互轉換的型別的乙個字段資訊。實際中經常會用到有個陣列,該陣列的內容正好是作為in裡面的引數列表。通過sql拼接的方式一定能夠實現,即便看起來比較繁瑣。下面是通過預編譯命令和引數佔...