Search code examples
sql-server-2008t-sqlcode-duplication

How to avoid duplication of the same query where only one parameter varies?


Using Microsoft SQL Server 2008, I have an SQL query similar to this:

insert into [Schema].[Table] ([A], [B], [C]) values (@A, 1, @C)
insert into [Schema].[Table] ([A], [B], [C]) values (@A, 2, @C)
                                                         ⁞
insert into [Schema].[Table] ([A], [B], [C]) values (@A, n, @C)

Is there a way to avoid writing n lines of code or at least make the query more compact, given that the query performance doesn't matter? If the performance would matter, would it be an issue?


Solution

  • Maybe you can utilize a loop for this specific case, ie:

    declare @counter int
    set @counter = 1
    
    while @counter < 10
    begin
      insert into [Schema].[Table] ([A], [B], [C]) values (@A, @counter, @C)
      set @counter = @counter + 1
    end