0

我想定製此存儲過程,以防萬一param值@TownId爲null將返回表中的所有數據。否則返回正確的數據。 在我的表中,TownId列中沒有空值。有nvarchar值。 我沒有成功獲取所有的數據,如果我送@ TownId = null,以從客戶端如果參數爲null,則返回所有值

ALTER PROCEDURE dbo.GetCustomersPageWiseWithTown 
@PageIndex INT = 1 
    ,@PageSize INT = 10 
    ,@PageCount INT OUTPUT 
    ,@TownId int 
AS 
    SET NOCOUNT ON; 
    SELECT ROW_NUMBER() OVER 
     (
       order by IsPaid desc 
     )AS RowNumber 
    ,b.Id 
    ,b.Name 
    ,b.Phone1 
    ,b.Town 
    ,b.Addess 
    ,b.IsPaid 
    ,b.DefaultImage 
    ,t.TownName 


INTO #Results 
    FROM BusinessFullData b 


    Left JOIN Towns t ON b.Town = t.Id 
    where ((b.IsVisable=1) and ([email protected])) 
    DECLARE @RecordCount INT 
    SELECT @RecordCount = COUNT(*) FROM #Results 

    SET @PageCount = CEILING(CAST(@RecordCount AS DECIMAL(10, 2))/CAST(@PageSize AS DECIMAL(10, 2))) 
    PRINT  @PageCount 

    SELECT * FROM #Results 
    WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1 

    DROP TABLE #Results 
RETURN 

多謝提醒,

回答

2

該條件只需添加到您的WHERE條款:

       V-------------V 
where ((b.IsVisable=1) and (@TownId IS NULL OR [email protected])) 

另請注意,IsVisible拼錯了。

+0

這不是正確的,在這種情況下,什麼都不會回來了,因爲在該表中的TownId值沒有空值。 – user2274204 2015-03-31 21:39:40

+0

@ user2274204再看一遍。空檢查在參數上,而不是在表列中。 – 2015-03-31 21:51:09

+0

@ user2274204沒關係。如果該參數爲null,則「@TownId IS NULL」將成立,第二個條件不起作用。 – 2015-03-31 21:58:52

0

處理可選參數的一種更好的方式是這樣的......

ALTER PROCEDURE dbo.GetCustomersPageWiseWithTown 
@PageIndex INT = 1 
,@PageSize INT = 10 
,@PageCount INT OUTPUT 
,@TownId INT 
AS 
BEGIN 
    SET NOCOUNT ON; 

DECLARE @Sql NVARCHAR(MAX); 
DECLARE @RecordCount INT; 

SET @Sql = N' 
    SELECT 
    ROW_NUMBER() OVER (order by IsPaid desc)AS RowNumber 
    ,b.Id 
    ,b.Name 
    ,b.Phone1 
    ,b.Town 
    ,b.Addess 
    ,b.IsPaid 
    ,b.DefaultImage 
    ,t.TownName 
       INTO #Results 
    FROM BusinessFullData b 
    Left JOIN Towns t ON b.Town = t.Id 
    where b.IsVisable = 1 ' 
    + CASE WHEN @TownId IS NOT NULL 
    THEN N' and b.Town = @TownId ' ELSE N'' END 

    + N' SELECT @RecordCount = COUNT(*) FROM #Results 

    SET @PageCount = CEILING(CAST(@RecordCount AS DECIMAL(10, 2))/CAST(@PageSize AS DECIMAL(10, 2))) 

    SELECT * FROM #Results 
    WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1' 

Exec sp_executesql @Sql 
        ,N'@PageIndex INT , @PageSize INT, @TownId int, 
        @RecordCount INT, @PageCount INT OUTPUT' 
        ,@PageIndex 
        ,@PageSize 
        ,@TownId 
        ,@PageCount OUTPUT 

END 
相關問題