2014-05-02 39 views
0

我正在使用SQL 2008R2。我有一個有56個可選參數的存儲過程。它被前端應用程序用於搜索表格。許多列包含NULL或空字符串。 當應用程序傳遞'%'作爲一個參數的值時,sproc返回匹配列的所有非空值的行。要求是返回所有非空和空匹配的行(即所有行)。要模擬它,我有這個小例子代碼:如何使用參數從存儲過程中返回空值,空值和非空值

-- table 
declare @foobar table 
(
column1 nvarchar(100) 
, column2 nvarchar(100) 
) 

-- dummy data 
insert into @foobar(column1, column2) 
select '100', 'high' union 
select '200', 'low' union 
select '300', null union 
select '400', 'medium' union 
select '500', '' union 
select '600', 'high' union 
select '700', '' union 
select '800', null 

-- parameter 
declare @column2 nvarchar(100) 
set @column2 = '%' 

-- This returns all non-null values. 
-- Requirement is to return all non-null and NULL values. 
select column1, column2 from @foobar 
where (column2 like @column2 + '%' or nullif(@column2, '') is null) 

/* 

'%' returns all records where value is not null 
Problem: Dev requires all values including null ones. 
Thought about the followings: 
1. Do a dynamic SQL based query and use sp_executesql: 

    -- create the WHERE clause 
    if @Column2 = '%' 
    @WHERE = 'AND (column2 like @column2 OR column is null)' 
    else 
    @WHERE = 'AND column2 like @column2 OR nullif(@column2, '') is null)' 
**/ 

我不喜歡動態查詢(我只是懶惰)。但是,爲此,我一直在嘗試動態查詢和sp_executesql。我不確定是否可以使用56個參數爲其創建動態查詢,其中許多參數將爲空(前端沒有提供任何參數)。我只是想知道是否有更好的方式做到這一點,而不使用動態查詢。

回答

0

你只需要對你的where條款稍作修改。

OR之前的第一部分將找到任何非空值。

第二部分將尋找空值只有當用戶inputed %

(column2 like @column2 + '%' or (@column2 = '%' and column2 is null)) 
+1

感謝它。此解決方案有效。我不知道爲什麼我沒有想到這個自己:)! – ahmjt

0

如何

WHERE (column2 LIKE @column2 + '%' OR @column2 = '%') 
+0

謝謝。此解決方案有效。不幸的是Anup有機會在你面前回答,所以我必須把它交給Anup – ahmjt