CREATE PROCEDURE dbo.Pro1 -- use schema prefix when creating objects!
@a NVARCHAR(32) = NULL -- 32 should match data type of Parameter2 column
AS
BEGIN -- wrap your body and indent for readability
SET NOCOUNT ON; -- should always turn off DONE_IN_PROC messages
SELECT columns -- please name your columns instead of SELECT *
FROM dbo.table1 -- use schema prefix when referencing objects
WHERE (Parameter2 = @a OR @a IS NULL); -- semi-colons please!
END
GO
在某些情况下,您可能会发现,如果您有很多这些可选参数,SQL Server 将为一组参数编译一个计划,而该计划对于不同的参数并没有多大好处。所以你可能想要这样的东西:
CREATE PROCEDURE dbo.Pro1
@a NVARCHAR(32) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'SELECT columns FROM dbo.table1 WHERE 1=1';
IF @a IS NOT NULL
SET @sql += ' AND Parameter2 = @a';
EXEC sp_executesql @sql,
N'@a NVARCHAR(32)',
@a;
END
GO