SQL Server adding the slashes to the date on the fly

前端 未结 2 1841
攒了一身酷
攒了一身酷 2021-01-29 12:38

I am trying to figure out how to add some sort of mask to my data. Currently I have a query like this:

SELECT [EmployeeTC_No] AS \"Employee TC#\"
      ,[pye_nla         


        
2条回答
  •  花落未央
    2021-01-29 13:10

    What you really need to do is fix your datatype of your column. varchar is not a one size fits all data type and should not be used to store dates. Like I said, 09282015 is not "after" 06242019, but according to your data, it is.

    You can fix your data by doing the below:

    USE testing;
    GO
    
    --Change the data to the ISO yyyyMMdd format
    UPDATE dbo.testing
    SET HireDate = CONVERT(varchar(8),CONVERT(date,STUFF(STUFF(SeparationDate,5,0,'/'),3,0,'/'),101),112),
        SeparationDate = CONVERT(varchar(8),CONVERT(date,STUFF(STUFF(SeparationDate,5,0,'/'),3,0,'/'),101),112);
    GO
    
    --Change the data types
    ALTER TABLE dbo.testing ALTER COLUMN HireDate date;
    ALTER TABLE dbo.testing ALTER COLUMN SeparationDate date;
    GO
    
    --And now you can select, and change the datatype to a format, with ease
    SELECT [EmployeeTC_No] AS [Employee TC#],
           [pye_nlast] AS [Name Last],
           [pye_nfirst] AS [Name First],
           [Dept] AS [Department],
           [pye_status] AS [Active],
           CONVERT(varchar(10),[HireDate],101) AS [Hire Date],
           CONVERT(varchar(10),[SeparationDate],101) AS [Separation Date]
      FROM [testing].[dbo].[testing];
    

提交回复
热议问题