Share via

T-SQL Scripting

Sara 441 Reputation points
2022-03-04T07:34:07.753+00:00

I have a SQL script to select and collect some info into temp table and populate data, And now I have a scenario where the table columns are different for different app versions and we use linked server to execute the script to multiple sql instances. so, it fails for specific sql instances with the latest application version which does not have that column.

Any idea on how to update the script to run for, i.e., if it is v1 it the stored procedure should run for that version and for V2 it should run the same procedure but the different script.

For ex: I want this script to run for V1 and I want line 2 for v2 in the same procedure

CREATE PROCEDURE [dbo].[sp_BoardServerTotals]

DELETE FROM BoardServer_Report - v1

DELETE FROM BoardServer - v2

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


3 answers

Sort by: Most helpful
  1. LiHong-MSFT 10,061 Reputation points
    2022-03-08T02:45:34.383+00:00

    Hi @Sara
    How about this:

    CREATE PROC Test_Proc  
    @app_version varchar(10)  
    AS  
    IF @app_version = 'v1'   
    BEGIN  
    DELETE FROM BoardServer_Report   
    END  
    ELSE IF @app_version = 'v2'   
    BEGIN  
    DELETE FROM BoardServer  
    END  
      
    EXEC emp_department @app_version='v1'  
    

    Best regards,
    LiHong

    Was this answer helpful?

    0 comments No comments

  2. Erland Sommarskog 134.7K Reputation points MVP Volunteer Moderator
    2022-03-04T23:01:44.63+00:00

    You would have to use dynamic SQL for your alternates, or else the procedure will not compile, at least as I understand it.

    So:

    IF @version = 1
       EXEC('DELETE FROM BoardServer_Report - v1')
    ELSE IF @version = 2
      EXEC('DELETE FROM BoardServer - v2')
    

    I fear that this can become quite messy.

    Was this answer helpful?

    0 comments No comments

  3. Naomi Nosonovsky 8,906 Reputation points
    2022-03-04T14:53:40.907+00:00

    You may try to use condition based on the @@SERVERNAME. As a side note, don't use sp_ for your procedures naming convention as many system stored procedures start with sp_. Anything except sp_ should be OK, you may use usp as the prefix, for example, to identify your stored procedures.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.