We help IT Professionals succeed at work.
Get Started

SQL Server 2008 R2 - @sql = IF OBJECT_ID, ALTER TABLE, DROP TABLE

1,446 Views
Last Modified: 2016-02-10
Hi experts I need your help with this,

I am very new to all this..

@TBLNM and @FILEID is a ResultSet parameter from SSIS that is "Foreach Loop Container" with a value/field in another table

      @fileId int,
      @TBLNM varchar (20),
Declare
            @sql nvarchar(4000)


I have this bit of code within a Stored Procedure and I know that it is not going to work:

select @sql = 'IF OBJECT_ID [dbo]. +('@TBLNM') IS NOT NULL' + 'ALTER TABLE [dbo].' + @TBLNM + ' DELETE CONSTRAINT [CK_' + @TBLNM + '_Max_File_ID] + ''
                  DROP TABLE [dbo].' + @TBLNM + '
                  FROM ' + @TBLNM + '
                  WHERE ' + @TBLNM + '.[FILE_ID] = ' + cast(@fileId as varchar(20))+ ' AND
                        EXISTS(SELECT #CLAIM_TEMP.CLM_KY
                                 FROM #CLAIM_TEMP
                                 WHERE #CLAIM_TEMP.CLM_KY = ' + @TBLNM + '.CLM_KY AND
                                    #CLAIM_TEMP.[FILE_ID] = ' + cast(@fileId as varchar(20)) + ')';


I want to be able to:
If table exit
Alter table constriants
Drop table
Where condition

I need to correct this code.

Please help and thanks
Comment
Watch Question
Facets Developer
Commented:
This problem has been solved!
Unlock 2 Answers and 13 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE