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