Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sp_MSforeachtable to execute procedure on each table

I want to print some dynamic query to execute a procedure on all tables in the database. This is what I've written so far -

EXEC SP_MSFOREACHTABLE '
    IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
       WHERE COLUMN_NAME="EMAIL_S" AND TABLE_NAME=PARSENAME("?",1))
    BEGIN
        PRINT ''EXEC DROPCONSTANT @TBLNAME=''+PARSENAME("?",1)
                  +'', @FLDNAME=''''EMAIL_S'''' ''
        PRINT CHAR(10)+CHAR(13)
    END
' 

The output is not what I expect it to be -

EXEC DROPCONSTANT @TBLNAME=bill, @FLDNAME='EMAIL_S'

But what I really want it -

EXEC DROPCONSTANT @TBLNAME='bill', @FLDNAME='EMAIL_S'
like image 753
Soham Dasgupta Avatar asked Dec 28 '22 03:12

Soham Dasgupta


2 Answers

How about this instead:

DECLARE @output NVARCHAR(MAX) = N'';

SELECT @output += CHAR(13) + CHAR(10) 
  + 'EXEC DROPCONSTANT @TBLNAME=''' + t.name + ''','
  + '@FLDNAME=''EMAIL_S'';'
  FROM sys.tables AS t
  INNER JOIN sys.columns AS c
  ON t.[object_id] = c.[object_id]
  WHERE c.name = 'EMAIL_S';

SELECT @output;
-- EXEC sp_executesql @output;
like image 184
Aaron Bertrand Avatar answered Dec 29 '22 17:12

Aaron Bertrand


You need to add a bunch of '.

PRINT ''DROPCONSTANT @TBLNAME=''''''+PARSENAME("?",1)+'''''', @FLDNAME=''''EMAIL_S'''' ''
like image 30
Mikael Eriksson Avatar answered Dec 29 '22 16:12

Mikael Eriksson