2013-11-27 24 views
0

誰能告訴我如何在Sql Server 2008中爲Null參數編寫此檢查。我需要知道如何在sql查詢中寫入條件語句,而不是在查詢部分之外。如何檢查存儲過程中的空值

查詢

DECLARE @SelItm NVARCHAR(max) 
DECLARE @Input1 VARCHAR(100) 
DECLARE @Input2 VARCHAR(100) 

SET selitm = 'Select * from table as tbla where tbla.Id='''[email protected]+ ''' (Case when @Input2 is not null then and tbla.supid='''[email protected]+ 
''' else '''' end)' 

EXEC Sp_executesql 
@SelItm 

回答

0

看起來你想念你@輸入1和其中的情況下應該開始之間的事情。

Select * 
from table as tbla 
where tbla.Id='''[email protected]+ ''' **SOMETHING_MISSING_HERE** 
(Case when @Input2 is not null then tbla.supid='''[email protected]+ ''' else '''' end) 

當你使用的情況下,你需要它是什麼的情況下,當時的一部分的情況下的「迴歸」(這麼說)元素 - 要比較的東西。

因此,例如:

'Select * 
from table as tbla 
where tbla.Id='''[email protected]+ ''' 
AND tbla.supid= 
    (Case when ''' + @Input2 + ''' is not null then '''[email protected]+ ''' else '''' end)' 

這將檢查tbla.Id = @Input1,如果@輸入2不爲空是supid = @Input2或者@輸入2是空的是supid = ''

通知相比,你的榜樣的supid =安置。

這是你需要的那條線嗎? 而如果是 - 那麼你可以通過使用ISNULL簡化聲明:

'Select * from table as tbla 
where tbla.Id='''[email protected]+ ''' AND tbla.supid= ISNULL(''' + @Input2 + ''' , '')' 

然而,只是爲了使問題更復雜一點;那麼你會遇到一個NULL問題,你試圖爲你的動態SQL添加NULL到一個字符串,並且添加NULL將導致NULL。 所以,在你的榜樣,以檢查NULL的最佳地點將是檢查查詢之前的@輸入2變量: 因此,當您有:

DECLARE @Input2 VARCHAR(100) 

則變量被設置後,你應該檢查在動態SQL語句中使用它之前NULL:

SET @Input2 = ISNULL(@Input2, '') 

而且然後使用變量的動態SQL語句。

+0

我希望它是類似如果參數不爲null然後包括在where子句否則不需要包括。請參閱我編輯的查詢。 – DonMax

+0

然後執行類似'AND tbla.supId = ISNULL(@ Input2,tlba.supId)' 那麼你不需要動態的sql字符串來執行。如果它爲空,則supId將與supId匹配,否則,它將與@ Input2 –

+0

比較它不適用於我''從表中選擇*作爲tbla 其中tbla.Id='''++Input1+' ''AND tbla.supid = ISNULL('''+ @ Input2 +''',tbla.supid)''。 – DonMax

0

我認爲你需要像這樣的每個可能null參數,讓我們先輸入1,我希望這段代碼會幫助你。

AND (Input1= @Input1 OR (Input1 IS NULL AND @Input1 IS NULL))