I have a table MyTable created by
CREATE TABLE MyTable
(
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Type] [int] NOT NULL,
[CreatedDate] [datetime] NOT NULL,
[ModifiedDate] [datetime] NOT NULL,
)
I want to check if a column exists in my table, and if it does, I want to copy the data to a different column, then drop the old column, like this:
IF (SELECT COLUMNPROPERTY(OBJECT_ID('MyTable'), 'Timestamp', 'Precision')) IS NOT NULL
BEGIN
UPDATE [dbo].[MyTable]
SET [CreatedDate] = [Timestamp]
ALTER TABLE [dbo].[MyTable]
DROP COLUMN [Timestamp]
END
GO
However, when I try to run this I get an error:
Invalid column name 'Timestamp'
How can I accomplish what I'm trying to do?
select columnproperty(...)sub-query return? I'm guessing it isn't null, so your update runs, and since timestamp really DOESN'T exist, you get that error.if()doesn't really apply when the sproc is parsed and your table is checke for aTimestampfield AT TIME OF COMPILE. You'd have to do it as dynamic sql. e.g.sql = 'UPDATE ..'; exec @sql-type thing