在连接选择中转换DateTime

时间:2014-01-14 08:07:50

标签: sql sql-server tsql

我想在此select中转换Date列,但会返回错误

SELECT 
   isnull(CAST([Barcode] AS VARCHAR), '') + ';' + 
   isnull(CAST([DocumentTypeID] AS VARCHAR), '') + ';' +  
   isnull(CAST([FlowStatusId] AS VARCHAR), '') + ';' + 
   isnull(CAST([DocumentStatusId] AS VARCHAR), '')  + ';' + 
   isnull(CAST([DATE] AS VARCHAR), '') AS 'DATE' 
FROM 
   dbo.PSDOC 
WHERE  
   DATEPART(m, Data) = DATEPART(m, DATEADD(m, -1, getdate()))

错误是:

  

无效的列名称“DATE”。严重程度16

1 个答案:

答案 0 :(得分:2)

正如错误所说。您没有名为“date”的列

似乎您的列名是DatA而不是日期。至于我可以在where子句中读到:

变化:

isnull(CAST([DATE] AS VARCHAR), '') AS 'DATE' FROM dbo.PSDOC 

isnull(CAST([DATA] AS VARCHAR), '') AS 'DATE' FROM dbo.PSDOC 

甚至更好地使用转换

isnull(CONVERT(varchar(20), [DATA], <format>), '') AS 'DATE' FROM dbo.PSDOC 

在此处找到您需要的格式Formats

除非你想要所有年份的前一个月,否则你应该考虑改变where子句

WHERE  DATEPART(m, Data) = DATEPART(m, DATEADD(m, -1, getdate()))

更改为

WHERE data >=dateadd(m, datediff(m, 0, current_timestamp)-1, 0) 
  and data < dateadd(m, datediff(m, 0, current_timestamp), 0)