Aleks
asked on
sql to copy nvarchar to date field
I have a table called 'users'
an nvarchar (25) field named 'visaexp'
and a datetime field named 'visaexpd'
The visa exp may have data such as : "NA" or "01/01/2012" etc. Some are actual dates.
I need to run a script that will copy the data from visaexp to visaexpd IF the value is a date
an nvarchar (25) field named 'visaexp'
and a datetime field named 'visaexpd'
The visa exp may have data such as : "NA" or "01/01/2012" etc. Some are actual dates.
I need to run a script that will copy the data from visaexp to visaexpd IF the value is a date
what platform?
ASKER
MS SQL 2008
For SQL Server, you can use ISDATE() function to assist you. Basically filter the data to records with ISDATE(visaexp) = 1, then UPDATE visaexpd = CONVERT(DATE, visaexpd).
EDIT: here is a demonstration.
The results:
MSDN: http://msdn.microsoft.com/en-us/library/ms187928(v=sql.105).aspx
EDIT: here is a demonstration.
DECLARE @users TABLE(
id BIGINT IDENTITY,
visaexp NVARCHAR(25),
visaexpd DATE,
PRIMARY KEY(id)
);
INSERT INTO @users(visaexp)
VALUES('NA'),
('01/01/2012'),
('01/30/2014'),
(NULL)
;
UPDATE @users
SET visaexpd = CONVERT(DATE, visaexp, 101)
WHERE ISDATE(visaexp) = 1
;
SELECT id, visaexp, visaexpd
FROM @users
;
The results:
id visaexp visaexpd
-------------------- ------------------------- ----------
1 NA NULL
2 01/01/2012 2012-01-01
3 01/30/2014 2014-01-30
4 NULL NULL
MSDN: http://msdn.microsoft.com/en-us/library/ms187928(v=sql.105).aspx
ASKER
Right .. I just don't know the syntax, not a real sql programmer hence the help
I was editing my comment to add a more concrete example. Please refresh my comment above for syntax help as well as Microsoft reference on CONVERT() function.
Here is the reference for ISDATE:
http://technet.microsoft.com/en-us/library/ms187347(v=sql.105).aspx
Note: I showed CONVERT with format code 101 (U.S. - mm/dd/yyyy) as an example, but you can leave this off or use a different code. Just be sure the consistency of your data, so that the resulting date is what you intended.
Here is the reference for ISDATE:
http://technet.microsoft.com/en-us/library/ms187347(v=sql.105).aspx
Note: I showed CONVERT with format code 101 (U.S. - mm/dd/yyyy) as an example, but you can leave this off or use a different code. Just be sure the consistency of your data, so that the resulting date is what you intended.
ASKER
Yeah .. the example doesn't really help me. I actually need the query that would copy the data from the tables I have. Ill wait for someone to create the query based on the table and fields info.
Something like:
Update users
set visaexpD = visaexp
IF .. visa exp is a date
Should be something simple.
Something like:
Update users
set visaexpD = visaexp
IF .. visa exp is a date
Should be something simple.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
:)