SQL Server dynamic queries

前端 未结 6 672
盖世英雄少女心
盖世英雄少女心 2021-01-07 04:21

I have 15 stored procedures that return data from a common table and then join that table with a specific table to retrieve inventory.

Example:

Commo         


        
6条回答
  •  抹茶落季
    2021-01-07 05:01

    Yep, you can generate an SQL statement dynamically and then execute it.

    For example,

    DECLARE @specificTableName nvarchar(50)
    DECLARE @specificColumnName nvarchar(50)
    
    SET @specificTableName = 'tblSpecific'
    SET @specificColumnName = 'colSpecific'
    
    DECLARE @sql nvarchar(4000)
    
    set @sql = 'SELECT ... FROM tblCommon c INNER JOIN ' +
    @specificTableName + ' s ON c.PrimaryKey = s.' + @specificColumnName
    
    
    exec (@sql)
    

提交回复
热议问题