SQL Server 存储过程中的可选参数?

问题描述:

我正在 SQL Server 2008 中编写一些存储过程,并想知道这里是否可以使用可选输入参数的概念?

I'm writing some stored procs in SQL Server 2008, and wondered if the concept of optional input parameters is possible here?

我想我总是可以为我不想使用的参数传入 NULL,检查存储过程中的值,然后从那里取出东西,但我很感兴趣,如果这个概念在这里可用.谢谢!

I suppose I could always pass in NULL for parameters I don't want to use, check the value in the stored proc, then take things from there, but I was interested if the concept is available here. Thanks!

你可以这样声明

CREATE PROCEDURE MyProcName
    @Parameter1 INT = 1,
    @Parameter2 VARCHAR (100) = 'StringValue',
    @Parameter3 VARCHAR (100) = NULL
AS

/* check for the NULL / default value (indicating nothing was passed */
if (@Parameter3 IS NULL)
BEGIN
    /* whatever code you desire for a missing parameter*/
    INSERT INTO ........
END

/* and use it in the query as so*/
SELECT *
FROM Table
WHERE Column = @Parameter