Hifza Rahim
Hifza Rahim

Reputation: 41

How to write the stored procedure query

I am trying to create a stored procedure to insert a new record into an INVOICE table

Details are:

How do I go about writing the stored procedure query to insert a new row in INVOICE when there is a FK and int columns?

This is what i did, but is incorrect:

CREATE PROC spNewCustomer_INVOICE
AS
BEGIN
    DECLARE @INV_NUMBER VARCHAR(50);
    DECLARE @CUS_CODE VARCHAR(50);
    DECLARE @INV_DATE VARCHAR(50);
AS 
    INSERT INTO INVOICE
    VALUES (@INV_NUMBER, @CUS_CODE, @INV_DATE)

Calling it:

EXEC spNewCustomer_INVOICE '2018', '20018', '2018-08-17'

Thanks for any help!

Upvotes: 0

Views: 98

Answers (1)

marc_s
marc_s

Reputation: 755491

First of all - you need to create parameters for your stored procedure - not internal variables.

Secondly, I would strongly recommend using the most appropriate datatype for each parameter - not just VARCHAR(50) for everything. Your table's columns are of type INT and DATETIME - use those types for your parameters!

And thirdly, I recommend to always explicitly specify the columns of the target table you're inserting into.

So all in all - try this code:

CREATE PROCEDURE NewCustomerInvoice
    @INV_NUMBER INT,
    @CUS_CODE INT,
    @INV_DATE DATETIME
AS
BEGIN
    INSERT INTO INVOICE (INV_NUMBER, CUS_CODE, INV_DATE)
    VALUES (@INV_NUMBER, @CUS_CODE, @INV_DATE);
END;

Then call this procedure with this command:

EXEC NewCustomerInvoice 
         @INV_NUMBER = 2018, 
         @CUS_CODE = 20018, 
         @INV_DATE = '20180817';

Upvotes: 2

Related Questions