What is dynamic SQL?

后端 未结 9 2278
暗喜
暗喜 2020-12-05 02:28

I just asked an SQL related question, and the first answer was: \"This is a situation where dynamic SQL is the way to go.\"

As I had never heard of

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 02:52

    Dynamic SQL is a SQL built from strings at runtime. It is useful to dynamically set filters or other stuff.

    An example:

    declare @sql_clause varchar(1000)  
    declare @sql varchar(5000)   
    
    
    set @sql_clause = ' and '    
    set @sql = ' insert into #tmp  
     select   
       *
    from Table 
    where propA = 1 '    
    
    if @param1 <> ''    
    begin    
       set @sql = @sql + @sql_clause + ' prop1 in (' + @param1 + ')'    
    end    
    if @param2 <> ''    
    begin    
       set @sql = @sql + @sql_clause + ' prop2 in (' + @param2 + ')'    
    end 
    
    exec(@sql)
    

提交回复
热议问题