最近在寫存儲過程的時候,發現一個問題,是關於存儲過程中字符串SQL中引入參數的問題。
且看下例:
declare @count int select @count=count(*) from student where Name in ('Chamy','Jundy')
print @count
如果我們要在上面句子中In后面引入參數:
那必須這么寫:
declare @count int declare @Names nvarchar(200) set @Names='''Chamy'',''Jundy''' declare @sql nvarchar(500) set @sql='select @count=count(*) from student where Name in ('+@Names+')' exec(@sql) print @count
這里我們選擇打印了@count參數,但是發現SQL執行會報錯,顯示@count參數沒有定義。想過才發現,由於我們exec的只是@sql里的SQL語句,確實是沒有定義@count參數的。而作為一個公用的參數,如果我想在@sql語句執行完后依然得到@count參數,那應該如何處理?
經過查找各種資料以及詢問資深的SQL開發人員,得到以下方式來解決如上問題:
declare @count int declare @Names nvarchar(200) set @Names='''Chamy'',''Jundy''' declare @sql nvarchar(500) set @sql='select @count=count(*) from student where Name in ('+@Names+')' EXEC sp_executesql @sql,N'@count int OUTPUT',@count OUTPUT print @count
我們注意到,能過在sp_executesql這個存儲過程中執行@sql參數,並重新定義@count參數,並使用@sql之外的參數@count進行輸出,就能很好的處理參數傳入的問題。
現列出sp_executesql存儲過程的說明和使用鏈接地址:http://technet.microsoft.com/zh-cn/library/ms188001.aspx
以上為本人在實際開發過程中發現的問題,希望對大家能有所幫助。
更多WEB開發技術請加群:Asp.Net高級群 號碼:261882616 博主以及同事和你共同探討感興趣的話題。