user556674
user556674

Reputation:

How to write Dynamic SQL for this?

I need to write a procedure which will have just execute statements.

Example:

Create Procedure dbo.allSPExecute( @id int)
as
begin

EXEC dbo.tic @day= 7,@name = 'Gname',@Type = 'Utype'
EXEC dbo.tic @day= 7,@name = 'tname',@Type = 'Utype'
EXEC dbo.gtype @day = 7,@Tname = 'UName_By',@Udept = 'Dept'

End

I have more than 50 statements like this.I have a Table which is Lookup:

ID  Name        SCol      Dcol       IOrd
1   dbo.tic     Gname     @name       1
1   dbo.tic     tname     @name       2
1   dbo.tic     Utype     @Type       1
1   dbo.tic     Utype     @Type       2
2   dbo.gtype   UName_By  @Tname      1
2   dbo.gtype   Dept      @Udept      1

Is there a way so that If i pass ID then it will take the values from the Lookup table and execute the procedure. Can anyone help?

EDIT: Changed the Data from Lookpup table and Create Procedure

Upvotes: 2

Views: 1331

Answers (3)

Sadhir
Sadhir

Reputation: 423

here is a solution that does not need cursors. I am using FOR XML keyword to concatenate strings together. I am doing this in two places - once for concatenating the list of parameters, and once for concatenating all the individual exec statements. I haven't tested this though, but i think this should be much faster than using cursors

CREATE PROCEDURE dbo.allSPExecute( @id INT ) 
AS  
BEGIN   
  DECLARE @query VARCHAR(MAX);   
  SELECT @query =   (
    SELECT ExecPart + ' ' + SUBSTRING(Params,2,LEN(Params)) + CHAR(10)
    FROM
    (
      SELECT 
        ExecPart ='EXEC ' +(SELECT TOP 1 Name FROM MyTable WHERE ID = @id) ,
        Params = (SELECT ', ' + Dcol + ' = ' + Scol 
                  FROM MyTable t1 WHERE ID = @id AND t1.IOrd = t.IOrd FOR XML PATH(''))
      FROM MyTable t
      WHERE ID = @id
      GROUP BY IOrd
    ) t
    FOR XML PATH('')   
  ) 

  EXEC (@query) 
END

Upvotes: 1

Fosco
Fosco

Reputation: 38526

Here's a cursor example written from scratch and untested:

declare @dynsql as nvarchar(300)
declare @tname as nvarchar(100)
declare @tscol as nvarchar(100)
declare @tdcol as nvarchar(100)

set @dynsql = ''

declare ticker as cursor for select Name, SCol, DCol from Lookup
open ticker
fetch next from ticker into @tname, @tscol, @tdcol

while @@FETCH_STATUS = 0
BEGIN

set @dynsql = 'EXEC ' + @tname + ' @day=7, ' + @tdcol + '=''' + @tscol + ''''

exec(@dynsql)

FETCH NEXT from ticker into @tname, @tscol, @tdcol
END

close ticker
deallocate ticker

Upvotes: 0

JNK
JNK

Reputation: 65217

Easiest solution - make your stored proc like this:

Create Procedure dbo.allSPExecute( @id int)
as

DECLARE @SQL varchar(max)

SET @SQL = 'USE MyDB'

SELECT @SQL = @SQL +
'EXEC ' + t.Name + ' @day = 7,' + t.Dcol + ' = ''' + t.Scol + ''
FROM MyTable t
WHERE t.id = @ID

EXEC (@SQL)

Upvotes: 4

Related Questions