存储过程的参数默认为默认约束值

时间:2019-04-17 18:10:54

标签: sql-server tsql default-constraint

我有一个Users表,其中有一个ImgPath列。我希望ImgPath列不为null,并且默认为特定路径。在表声明中,我有这个:

[ImgPath] VARCHAR(256) NOT NULL 
    CONSTRAINT [DF_Users_ImgPath] DEFAULT ('/images/default.jpg')

我有一个SaveUser存储过程,它是一个合并语句,可以用新的ImgPath更新用户或用关联的ImgPath创建新用户。

CREATE PROCEDURE [dbo].[SaveUser] 
    (@UserId UNIQUEIDENTIFIER, 
     @ImgPath VARCHAR(256)) 
AS
    MERGE [dbo].[Users] AS TARGET
    USING (SELECT @UserId, @ImgPath) AS SOURCE ([UserId], [ImgPath]) ON (TARGET.[UserId] = SOURCE.[UserId])

    WHEN MATCHED THEN
        UPDATE 
            SET TARGET.[ImgPath] = SOURCE.[ImgPath]

    WHEN NOT MATCHED BY TARGET THEN
        INSERT ([UserId], [ImgPath])
        VALUES (SOURCE.[UserId], SOURCE.[ImgPath]);

如何编辑存储过程,以便如果ImgPath为null,则默认为DEFAULT CONSTRAINT值,而表声明和存储过程中都没有该值?

如果我发送NULL或将@ImgPath的默认值设置为NULL,这将不起作用,因为NULL会覆盖默认值,并且由于该列不可为空,因此会引发错误。

COALESCEISNULL不喜欢DEFAULT作为后备参数。

我也不想让讨厌的if / case语句执行两个MERGE语句。

1 个答案:

答案 0 :(得分:0)

不像我应该的那样对MERGE表现出厌恶,但这可能有用。

CREATE PROCEDURE [dbo].[SaveUser] 
    (@UserId UNIQUEIDENTIFIER, 
     @ImgPath VARCHAR(256)) 
AS
    MERGE [dbo].[Users] AS TARGET
    USING (SELECT @UserId, @ImgPath) AS SOURCE ([UserId], [ImgPath]) ON (TARGET.[UserId] = SOURCE.[UserId])

    WHEN MATCHED AND SOURCE.[ImgPath] is not null THEN
        UPDATE 
            SET TARGET.[ImgPath] = SOURCE.[ImgPath]


    WHEN NOT MATCHED BY TARGET AND SOURCE.[ImgPath] is not null THEN
        INSERT ([UserId], [ImgPath])
        VALUES (SOURCE.[UserId], SOURCE.[ImgPath])
    WHEN NOT MATCHED BY TARGET AND SOURCE.[ImgPath] IS NULL then
        INSERT ([UserId])
        VALUES (SOURCE.[UserId]);

仅当ImgPath具有值时,此应该摆弄ImgPath。