如何在T_SQL存储过程中添加可选参数?

时间:2019-02-25 20:52:20

标签: sql-server

假设我有以下参数:

@firstName varchar(50), @middleName varchar(50), @LastName varchar(50)

我希望中间名是可选的,如果没有将中间名作为输入参数传递,如何返回不带中间名的值(@portalUserName)?

PS:如果用户具有中间名(即,如果中间名的值不为空),我需要在用户名中添加中间名第一个字符

CREATE PROCEDURE [dbo].[cst_sproc_UserName_Get]    
    (@firstName VARCHAR(50), 
     @middleName VARCHAR(50),
     @LastName VARCHAR(50)   
    )    
AS    
BEGIN   
    DECLARE @portalUserName VARCHAR(50)  

    SET @portalUserName = SUBSTRING(UPPER(RTRIM(@firstname)), 1, 1) + 
                          SUBSTRING(UPPER(RTRIM(@firstname)), 1, 1) + 
                          LOWER(RTRIM(@LastName))  

    IF NOT EXISTS (SELECT 'TRUE' FROM wpUser WHERE UserCode = @portalUserName)  
    BEGIN  
        SELECT @portalUserName UserCode  
        RETURN
    END 
END

1 个答案:

答案 0 :(得分:2)

要将参数设为可选,您需要为其提供默认值,该值可以为NULL

CREATE  PROC [dbo].[cst_sproc_UserName_Get]    
    (    
     @firstName varchar(50), 
     @middleName varchar(50) = NULL,
     @LastName varchar(50)   

    )    
    AS    
    BEGIN   

    Declare @portalUserName varchar(50)  
    SET @portalUserName = SUBSTRING(upper(RTRIM(@firstname)),1,1)+ SUBSTRING(upper(RTRIM(@firstname)),1,1) + lower(RTRIM(@LastName))  

    IF NOT EXISTS (SELECT 'TRUE' FROM wpUser WHERE UserCode = @portalUserName)  
    BEGIN  

     SELECT @portalUserName UserCode  
     Return  

    END 

但是要调用它,您需要遵循最佳实践并使用参数命名来调用过程。

EXEC [dbo].[cst_sproc_UserName_Get] @firstName = 'Luis', @LastName = 'Cazares';