Question

My Select statements work fine individually. But can I have one stored procedure with all of them instead of having multiple procedures?

ALTER PROCEDURE [dbo].[zPrintAll]
@PrintVariable varchar(10),
@SuppliedKey      varchar(15)
AS
BEGIN
    IF(@PrintVariable='ONE')
        BEGIN
            SELECT  *
            FROM  Table1 INNER JOIN Table2 ON Table1.key=Table2.key
            WHERE   Table2.key='@SuppliedKey'
        END
    IF(@PrintVariable='TWO')
        BEGIN
            SELECT  *
            FROM  Table3 INNER JOIN Table4 ON Table3.key=Table4.key
            WHERE   Table3.key='@SuppliedKey'
        END

END

EDIT: This is for a detailed print function. When I supply a PersonID, I go into each department and print their bill in that department. I will Print a main bill that has atleast 20 departments. If My Print variable says 'Clothes', I would print the required fields from the 'Clothing department' for a PID. If My Print variable says 'Shoes', I would print the required fields from the 'Shoe department' for the PID and so on. I have a crazy amount of procedures already and don't want to add another bunch of Select Statements in there.

I have done this for a Procedure that either 'Updates' or 'Deletes' based on a flag but it doesn't seem to be working here.

Was it helpful?

Solution 2

There is nothing wrong with the query but I got the syntax wrong when I replaced the static key with the variable.

ALTER PROCEDURE [dbo].[zPrintAll]
@PrintVariable varchar(10),
@SuppliedKey      varchar(15)
AS
BEGIN
    IF(@PrintVariable='ONE')
        BEGIN
            SELECT  *
            FROM  Table1 INNER JOIN Table2 ON Table1.key=Table2.key
            WHERE   Table2.key=@SuppliedKey
        END
    IF(@PrintVariable='TWO')
        BEGIN
            SELECT  *
            FROM  Table3 INNER JOIN Table4 ON Table3.key=Table4.key
            WHERE   Table3.key=@SuppliedKey
        END
END

So, it is @SuppliedKey instead of '@SuppliedKey'

OTHER TIPS

ALTER PROCEDURE [dbo].[zPrintAll]
@PrintVariable varchar(10),
@SuppliedKey      varchar(15)
AS
BEGIN

    BEGIN
        SELECT  * 
        FROM  Table1 INNER JOIN Table2 ON Table1.key=Table2.key

        UNION ALL
        SELECT  *
        FROM  Table3 INNER JOIN Table4 ON Table3.key=Table4.key

        WHERE @SuppliedKey = CASE WHEN @PrintVariable='ONE' THEN Table2.key
         WHEN @PrintVariable='TWO' THEN Table3.key ELSE '' END 
    END

END
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top