I have the following sql statement
Code Snippet
UPDATE OtherCall SET [Date] = CONVERT(NVARCHAR(50),CONVERT(DATETIME,[Date],103),111)
ALTER TABLE OtherCall ALTER COLUMN [Date] DATETIME
I am converting a nvarchar to a datetime on one of the columns in the table. However, I don't want to execute this if the conversion has already executed.
I was thinking of having a if statement that if the column is not a datetime then alter the column.
I am unsure how to write the if statement to check for the data type of that column.
Many thanks for any help,
Steve
If you're intention is to ultimately convert the datatype, what's preventing you from initially setting the datatype as datetime?
I know this doesn't answer your question, but I'm curious.
Adamus
|||Hello,The table was created initially with a nvarchar. This is a live database and the dates that have already been entered have to be formated in order for the alter column will work.
If the customer runs this script more than once, I don't want to have to execute the alter statement again.
Many thanks,
Steve
|||
There's really not a problem if that statement executes EVEN if the datatype has been previously changed.
However, if you need to:
Code Snippet
IF NOT EXISTS
( SELECT DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE ( TABLE_NAME = 'OtherCall'
AND COLUMN_NAME = 'Date'
AND DATA_TYPE = 'datetime'
)
)
BEGIN
UPDATE OtherCall
SET [Date] = convert( nvarchar(50), convert( datetime, [Date], 103), 111)
ALTER TABLE OtherCall ALTER COLUMN [Date] datetime
END |||Try the below SQL Statement, this is my version of solution there may be other ways to
' Returns row if the column is already converted to the required data type
IF EXISTS (select c.name, c.xtype from sysobjects o, syscolumns c where o.id = c.id and o.name = tablename and c.xtype= 61(xtype value of datatime datatype, can be found in systypes table in master database) and c.name =column name)
BEGIN
// The column is already converted to datatime format. In your case this step will be blank
END
ELSE
BEGIN
// The column is not in datatime datatype so we need to convert it. Below is your code for conversion
UPDATE OtherCall SET [Date] = CONVERT(NVARCHAR(50),CONVERT(DATETIME,[Date],103),111)
ALTER TABLE OtherCall ALTER COLUMN [Date] DATETIME
END
No comments:
Post a Comment