Reputation: 1295
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.
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
Are local variable declared only used for SQL query statement like
select *
from table
where date_key = @DATE_Key?
Upvotes: 0
Views: 62
Reputation: 10817
There is more than one error.
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
Upvotes: 3
Reputation: 1270713
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.
Upvotes: 1
Reputation: 874
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.
You can easily convert a DATE to a VARCHAR and then to a INT, this way:
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
Upvotes: 0