We help IT Professionals succeed at work.
Get Started

SQL Server - Stored Procedure, If Exits - Delete Constaint & Tablel

Last Modified: 2014-05-02
Hi Experts,

I am very new to all this.

I need help this is giving me errors.

I am passing parameters from SSIS to the SP in SQL Server 2008 R2
      @fileId int,
      @TBLNM varchar(40),

That is working fine I can tell by the test I do:
      PRINT 'THIS IS THE VALUE OF FILE_ID: ' + cast(@fileId as varchar(20))

I would like to first check if a Constaint exist, if it does delete and the table.

I have this code:
      PRINT 'THIS IS THE VALUE OF FILE_ID: ' + cast(@fileId as varchar(20))
      SET @rc = 1
      WHILE @rc > 0
            BEGIN TRAN
            SELECT @sql = 'IF OBJECT_ID  (''dbo.' + @TBLNM + ''') IS NOT NULL  ' +
           'ALTER TABLE dbo.' + @TBLNM + ' DROP CONSTRAINT CK_' + @TBLNM + '_Max_File_ID ;' +
           ' DELETE FROM ' + @TBLNM + ' AS T' +
           ' WHERE T.[FILE_ID] = ' + cast(@fileId as varchar(20))+ ' AND
                        EXISTS(SELECT #CLAIM_TEMP.CLM_KY
                                 FROM #CLAIM_TEMP
                                 WHERE #CLAIM_TEMP.CLM_KY = T.CLM_KY AND
                                       #CLAIM_TEMP.FILE_ID = ' + cast(@fileId as varchar(20)) + ')'
                  exec sp_executesql @sql;
                  SET @rc = @@ROWCOUNT
            COMMIT TRAN


But it is not working correctly

"Incorrect syntax near the keyword 'AS'.".
Also would like to know if this:
'IF OBJECT_ID  (''dbo.' + @TBLNM + ''') IS NOT NULL  
Takes care of both Constaint & Table Existing

Please help and thanks...
Watch Question
Senior DBA
Most Valuable Expert 2018
Distinguished Expert 2019
This problem has been solved!
Unlock 1 Answer and 6 Comments.
See Answer
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