我想自定义这个存储过程,如果该参数值@TownId为null,则返回表中的所有数据。否则返回正确的数据。 在我的表中,TownId列中没有空值。有nvarchar值。 如果我从客户端发送@ TownId = 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 (b.Town=@TownId))
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
非常感谢您提供建议,
答案 0 :(得分:2)
只需将该条件添加到WHERE
子句:
V-------------V
where ((b.IsVisable=1) and (@TownId IS NULL OR b.Town=@TownId))
另请注意,IsVisible
拼写错误。
答案 1 :(得分: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