存储过程 NULL 参数
我有一个数据库表,我正在尝试使用存储过程对其进行更新/插入。让我们像这样定义表:
CREATE TABLE Foo
(
Id INT IDENTITY(1, 1),
Name VARCHAR(256) NOT NULL,
ShortName VARCHAR(32),
Sort INT
);
我编写了一个类似于以下内容的存储过程:
CREATE PROCEDURE Put_Foo
(
@Id INT = NULL OUTPUT,
@Name VARCHAR(256),
@ShortName VARCHAR(32) = NULL,
@Sort INT = NULL
)
AS
BEGIN
SET NOCOUNT ON;
SELECT
@Id = F.Id
FROM
Foo AS F
WHERE
F.Name = @Name;
IF (@Id IS NOT NULL)
BEGIN
UPDATE
Foo
SET
ShortName = @ShortName,
Sort = @Sort
WHERE
Id = @Id;
END
ELSE
BEGIN
INSERT
INTO Foo
(
Name,
ShortName,
Sort
)
VALUES
(
@Name,
@ShortName
@Sort
);
SET @Id = SCOPE_IDENTITY();
END
RETURN;
END;
我已经大大简化了我正在处理的数据结构,但我希望这符合我的观点。我的问题是关于如何处理参数的。有没有办法在过程中确定 @Sort 是否作为 NULL 传入或通过参数列表中的默认声明设置 NULL?
编辑:
这样做的目的是我不希望 NULL 参数覆盖 UPDATE 语句中的任何列,除非它们以这种方式显式传递。
I have a database table I am trying to do an UPDATE/INSERT to with a stored procedure. Let's define the table like so:
CREATE TABLE Foo
(
Id INT IDENTITY(1, 1),
Name VARCHAR(256) NOT NULL,
ShortName VARCHAR(32),
Sort INT
);
I have written a stored procedure similar to the following:
CREATE PROCEDURE Put_Foo
(
@Id INT = NULL OUTPUT,
@Name VARCHAR(256),
@ShortName VARCHAR(32) = NULL,
@Sort INT = NULL
)
AS
BEGIN
SET NOCOUNT ON;
SELECT
@Id = F.Id
FROM
Foo AS F
WHERE
F.Name = @Name;
IF (@Id IS NOT NULL)
BEGIN
UPDATE
Foo
SET
ShortName = @ShortName,
Sort = @Sort
WHERE
Id = @Id;
END
ELSE
BEGIN
INSERT
INTO Foo
(
Name,
ShortName,
Sort
)
VALUES
(
@Name,
@ShortName
@Sort
);
SET @Id = SCOPE_IDENTITY();
END
RETURN;
END;
I've greatly simplified the data structures I am dealing with but I hope this serves my point. My question is in regards to how the parameters are processed. Is there a way to determine within the procedure if @Sort was passed in as NULL or set NULL by the default declaration in the parameter list?
EDIT:
The purpose of this is that I don't want NULL parameters to override any columns in the UPDATE statement unless they are explicitly passed in that way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,你无法检测@Sort如何变成NULL。如果您的目标是捕获显式设置的时间与默认设置的时间,我建议使用不同的默认值(可能是通常不会使用的默认值,例如 -1)。然后你可以假设如果@Sort为NULL,它是显式传入的,但如果它是-1,你知道它是默认设置的。
No, you can't detect how @Sort became NULL. If your goal is to capture when it is explicitly set versus it being set by the default, I would suggest using a different default value (maybe one that wouldn't normally be used, like -1). Then you can assume that if @Sort is NULL, it was explicitly passed in, but if it is -1, you know it was set by default.
我想这就是你所寻找的。如果其中一个参数为空,它将使用数据库中的值更新它。另一种选择是一次更新一列。
I think this is what your looking for. If one of the parameters is null, it will updatedit with the value in the database. The other option is update one column at a time.
取出默认值,然后调用proc的代码必须提供一个值(可以是真实值,也可以是NULL)
Take out the default value and and then the code calling the proc must provide a value (either a real value or NULL)