简体   繁体   中英

How convert nvarchar column from a existing table to date? SQL Server

I have a table in SQL Server created like this:

CREATE TABLE nombres
(
     nombre varchar (200) not null,
     fecha_nac char (10) not null,
     fecha_alta char (10) not null,
)

I created a stored procedure to fill the table quickly. The next step is "formatting" the dates made into date format. I saw that I can use

SELECT CONVERT(datetime, 'a string', 100)

In this case I want use my column as parameter like this

SELECT CONVERT (datetime, select fecha_nac from nombres, 100)

but I get an error.

I will be thankful if I get any help

With the date format you have, ( mm-yyyy-dd ), you can do some string manipulation to get it to dd-mm-yyyy and then it can be parsed as a DATE with format 103 .

WITH cte AS (
  SELECT '11-1994-27' fecha_nac
)
SELECT 
  CONVERT(DATE, SUBSTRING(fecha_nac, 9, 2) + '-' + SUBSTRING(fecha_nac, 0, 8), 103)
FROM cte;

-- 1994-11-27

Your fecha_alta format is easier, it can be parsed right away with format 102.

WITH cte AS (
  SELECT '2012-1-12' fecha_alta UNION ALL 
  SELECT '1994-4-5'
)
SELECT 
  CONVERT(DATE, fecha_alta, 102)
FROM cte;

-- 2012-01-12
-- 1994-04-05
DECLARE @site_value INT;
SET @site_value = 1;
WHILE @site_value <= (SELECT COUNT(nombre) FROM nombres)
    BEGIN
        WITH MyCte AS 
        (
            SELECT fecha_nac,number= ROW_NUMBER() OVER (ORDER BY dbo.nombres.fecha_nac) 
            from dbo.nombres 
        )
        SELECT convert(datetime,(SELECT MyCte.fecha_nac from MyCte WHERE number=@site_value), 101)
        SET @site_value = @site_value + 1;
    END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM