存儲過程筆記

 1、使用sql模板。如下所示:

通常的做法:set @SQL='select '+@col+' from '+@tbl+'

較好的方法是:

set @SQL_Template='select $col from $tbl'

set @sql = replace(@SqL_template,'$col',@col)

 

2、使用constraint或unique index來儘可能早的發現錯誤,使用@@error可以用來檢查上一個SQL執行的結果,如果不爲0就是發生錯誤,可以立刻返回,以避免進一步的錯誤。

 

3、使用Microsoft Visual Studio 進行存儲過程調試。

 

4、使用遊標

use database1
declare my_cursor cursor scroll dynamic
/**//* scroll表示可隨意移動遊標指        針(否則只能向前),dynamic表示可以讀寫遊標(否則遊標只讀) */
for
select productname from   product

open my_cursor
declare @pname sysname
fetch next from my_cursor into @pname
while ( @@fetch_status = 0 )
  
begin
    
print ' Product Name: ' + @pname
    
fetch next from my_cursor into @pname
  
end
fetch first from my_cursor into @pname
print @pname
/**//* update product set productname='zzg' where current of my_cursor */
/**//* delete from product where current of my_cursor */
close my_cursor
deallocate my_cursor

 

5、判斷臨時表是否存在

if   object_id('tempdb..#tempTable')   is   not   null  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章