如何将默认日期和时间值传递到存储过程?

时间:2017-01-05 06:26:21

标签: sql sql-server stored-procedures

我正在尝试创建一个存储过程,其中我根据Null或Not Null传递列值。我已将默认值getdate()设置为列' datetime'并将其设置为非null。但是在将值传递到列的同时,我不知道我需要传递给' datetime'列,因为它将存储默认值。

这是我想要完成的事情:

ALTER PROCEDURE [dbo].[usp_insert_test2]
    (@testid int, 
     @age int, 
     @salary decimal, 
     @name varchar(250),
     @datetime datetime = default,
     @gender bit) 
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO test2 
    VALUES (@testid, @age, @salary, @name, @datetime, @gender)
END

我想知道我应该在@datetime传递什么:

enter image description here

4 个答案:

答案 0 :(得分:2)

简单的方法是使用COALESCE

INSERT INTO test2 (testid,age,salaray,name,[datetime],gender)
VALUES (@testid, @age, @salary, @name, coalesce(@datetime,getdate()), @gender)

或者基于@datetime参数的值,您需要框架插入查询。从插入中删除datetime列,并在NULL时选择列表,以便填充默认值

If @datetime is null
    INSERT INTO test2 (testid,age,salaray,name,gender)
    VALUES (@testid, @age, @salary, @name, @gender)
Else 
    INSERT INTO test2 (testid,age,salaray,name,[datetime],gender)
    VALUES (@testid, @age, @salary, @name, @datetime, @gender)

您还可以考虑更改接受table type作为输入的过程,以便一次可以插入多条记录

答案 1 :(得分:0)

感谢您的宝贵帖子。我纠正了它:

ALTER PROCEDURE [dbo].[usp_insert_test2]
    (
      @testid int, 
      @age int,
      @salary decimal,
      @name varchar(250),
      @gender bit
    ) 
AS BEGIN
    SET NOCOUNT ON;
insert into test2 (testid,age,salary,name,gender) values (@testid,@age,@salary,@name,@gender)
END

答案 2 :(得分:0)

将日期未提供给存储过程时,将默认值设置为当前日期。

以下是答案。

_.minBy(masterArray, _.size) -> [1, 2]

答案 3 :(得分:0)

您根本不需要传递@datetime变量。我使用了前面提供的示例。

ALTER PROCEDURE [dbo].[usp_insert_test2]
    (@testid int, 
     @age int, 
     @salary decimal, 
     @name varchar(250),
     @gender bit) 
AS
BEGIN
    SET NOCOUNT ON;
    INSERT INTO test2 
    VALUES (@testid, @age, @salary, @name, GETDATE(),@gender)
END

请注意,您可以使用CONVERT关键字和各种可用格式根据您的要求修改GETDATE()函数。