Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename a column if it exists in a table

I am trying to rename a column if it is exists

GO

IF EXISTS(SELECT 1 FROM sys.columns WHERE [name] = N'MinDuration'
           AND [object_id] = OBJECT_ID(N'Category'))
BEGIN
    sp_RENAME 'Category.MinDuration', 'SingleDuration' , 'COLUMN'
END

GO

But getting error Incorrect syntax near sp_RENAME. Expecting CONVERSATION, DIALOG, DISTRIBUTED or TRANSACTION

How can I rename my column if it exists in the table?

like image 679
Billa Avatar asked Oct 27 '25 03:10

Billa


1 Answers

Try putting exec first:

IF EXISTS(SELECT 1 FROM sys.columns WHERE [name] = N'MinDuration'
           AND [object_id] = OBJECT_ID(N'Category'))
BEGIN
    EXEC sp_RENAME 'Category.MinDuration', 'SingleDuration' , 'COLUMN'
END;
like image 99
Gordon Linoff Avatar answered Oct 28 '25 18:10

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!