简体   繁体   English

插入之前,Microsoft SQL Server转换中的存储过程

[英]Stored procedure in Microsoft SQL Server conversion before inserting

I am trying to create a stored procedure that does manipulation of parameter passed in before inserting it into my table. 我试图创建一个存储过程,该过程对将传入的参数插入表中之前的参数进行操作。 One of the columns in my table is called DATE_CHANGED and basically what I gg to do here is to change a passed date parameter like December 1st 2017 to 20171201. This is an int value. 我表中的一列称为DATE_CHANGED ,基本上我要在这里执行的操作是将传递的日期参数(如2017年12月1日)更改为20171201。这是一个int值。

I wrote a stored procedure like this: 我写了这样一个存储过程:

CREATE PROCEDURE date_generate
     @startDate DATE
AS
BEGIN
    DECLARE @DATE_KEY INT

    @DATE_KEY = CONVERT(INT, FORMAT(@startDate, 'YYYYMMDD')

    INSERT INTO table date_key = @DATE_KEY
END

However I get an error 但是我得到一个错误

Incorrect syntax near '@DATE_KEY '@DATE_KEY附近的语法不正确

Are local variable declared only used for SQL query statement like 是否声明局部变量仅用于SQL查询语句,例如

select * 
from table 
where date_key = @DATE_Key?

There is more than one error. 有多个错误。

  • Use SET to assign values to a variable. 使用SET将值分配给变量。
  • Have a look at INSERT statement too. 也看一下INSERT语句。

CREATE PROCEDURE date_generate
    @startDate date
    AS
    BEGIN
        DECLARE @DATE_KEY int;
        SET @DATE_KEY = CONVERT(int, format(@startDate, 'YYYYMMDD'));
        INSERT INTO DATE_CHANGED (date_key) 
        VALUES (@DATE_KEY);
    END

This seems really strange. 这看起来真的很奇怪。 You don't even need a local variable. 您甚至不需要局部变量。 Based on your code, you could write: 根据您的代码,您可以编写:

create procedure date_generate (
    @startDate date
) as
begin
    insert into table (date_key)
        values ( convert(int, format(@startDate, 'YYYYMMDD')) );
end;  -- date_generate

Or, I might write: 或者,我可能会写:

create procedure date_generate (
    @startDate date
) as
begin
    insert into table (date_key)
        values ( year(@startDate) * 10000 + month(@startDate) * 100 + day(@startDate) );
end;

Why you would have a table with a single date on each row doesn't really make sense to me. 为什么在每行上只有一个日期的表对我来说真的没有意义。 Why you would be storing that "date" as an integer also doesn't make sense. 为什么将“日期”存储为整数也没有意义。

As far as I've understood, your stored procedure accepts a DATE as a parameter, but you need to do an INSERT with an INT. 据我了解,您的存储过程接受DATE作为参数,但是您需要使用INT进行INSERT。

You can easily convert a DATE to a VARCHAR and then to a INT, this way: 您可以通过以下方式轻松地将DATE转换为VARCHAR然后转换为INT:

DECLARE @DateASInt INT = CAST(CONVERT(VARCHAR(8), @startDate, 112) AS INT);

So, your stored procedure will be like this: 因此,您的存储过程将如下所示:

CREATE PROCEDURE date_generate
    @startDate date
    AS
    BEGIN
        INSERT INTO date_key
            VALUES (CAST(CONVERT(VARCHAR(8), @startDate, 112) AS INT));
    END

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM