Search code examples
sqlsql-serverstored-proceduresinsert-intoselect-into

Insert Into Select stored procedure not working inserting NULL


My first time creating a stored procedure here please go easy on me. I was trying to SELECT my data from Table 1 (EmpTBL), then INSERT it into Table 2 (EventTBL)

I think the culprit is this line right here:

@Ename varchar(250) = NULL, 
@Edate varchar(250) = NULL,

I think my logic is in the right direction I just dont why it doesn't work.

Not sure what to do next.

ALTER PROCEDURE spBdayEmp
   (@Ename varchar(250) = NUll,
    @Edate varchar(250)= NUll,
    @Etype varchar(250)  = 'Bday')
AS 
    INSERT INTO EventTBL(EventName, EventDate, EventType)
    VALUES (@Ename, @Edate, @Etype)

    SELECT
        @Ename =  (Ename + ' ' + Lname),    
        @Edate =  DATEADD(YY, DATEPART(YYYY, GETDATE()) - DATEPART(YYYY,dateOfBirth), dateOfBirth) 
    FROM 
        EmpTBL   
    WHERE  
        DATEADD( Year, DATEPART( Year, GETDATE()) - DATEPART( Year, DateOfBirth), DateOfBirth) BETWEEN CONVERT( DATE, GETDATE()) AND CONVERT( DATE, GETDATE() + 30); 

how would i get the values for? @Ename, @Edate?

i would like the result of the SELECT query "Ename + ' ' + Lname," equals to "@Ename" and " DATEADD(YY, DATEPART(YYYY, GETDATE()) - DATEPART(YYYY,dateOfBirth), dateOfBirth)," equals to "@Edate"?


Solution

  • after reading INSERT statement cannot contain a SELECT statement -sql server2012

    i realized i had it all wrong so after some experimenting i finally found a solution.

    ALTER PROCEDURE spBdayEmp
    AS INSERT INTO 
    EventTBL SELECT  (Ename + ' ' + Lname), DATEADD(YY, DATEPART(YYYY, GETDATE()) - DATEPART(YYYY,dateOfBirth), dateOfBirth),('Bday')FROM 
    EmpTBL WHERE DATEADD( Year, DATEPART( Year, GETDATE()) - DATEPART( Year, DateOfBirth), DateOfBirth) BETWEEN CONVERT( DATE, GETDATE()) AND CONVERT( DATE, GETDATE() + 30);
    

    Thanks for everyone who's been trying to help out!