如何以正确的格式将datetime变量传递到SQL字符串中?

时间:2019-04-10 03:09:04

标签: sql sql-server

我正在使用SQL脚本在SQL Server 2014 Management Studio中工作。

我的问题:我有2个返回日期时间的变量,即2019-04-01 00:00:00.000,我试图将这些变量添加到SQL字符串中,但是当我这样做时,格式会丢失,并且会转换到此:Apr 1 2019 12:00 AM。该格式的日期在我的SQL脚本中不起作用

我已经尝试了多种转换和强制转换代码,但是它根本不起作用,下面是我在@InvoiceTrue变量中得到的内容:

left join table1 payment on l.LedgerID = payment.LedgerID
left join table2 i on payment.InvoiceID = i.InvoiceID
where l.BusinessDate between 'Apr  1 2019 12:00AM' and 'Apr  7 2019 12:00AM' 
order by l.LedgerID

如果从上方看,日期时间格式将丢失。

这是我的SQL代码:

Declare
    @innerBeginDate datetime = '2019-04-01'
,   @innerEndDate datetime = '2019-04-07'
,   @InvoiceTrue varchar(max)

Select @InvoiceTrue = N'
    left join table1 payment on l.LedgerID = payment.LedgerID
    left join table2 i on payment.InvoiceID = i.InvoiceID
    where l.BusinessDate between ''' +  CAST(@innerBeginDate as varchar) + ''' and ''' + CAST(@innerEndDate as varchar) + ''' order by l.LedgerID'''

select @InvoiceTrue

将参数传递到字符串后,我需要保持相同的日期时间格式,以始终像2019-04-01 00:00:00.000。我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

DECLARE @date DATETIME = '2019-04-01'
select convert(varchar, @date, 13);  

Output is: 01 Apr 2019 00:00:00:000

如果您希望查看运行中的不同转换格式,则可以使用以下代码段:

DECLARE @counter INT = 0
DECLARE @date DATETIME = '2019-04-01'

CREATE TABLE #dateFormats (dateFormatOption int, dateOutput varchar(40))

WHILE (@counter <= 150 )
BEGIN
   BEGIN TRY
      INSERT INTO #dateFormats
      SELECT CONVERT(varchar, @counter), CONVERT(varchar,@date, @counter) 
      SET @counter = @counter + 1
   END TRY
   BEGIN CATCH;
      SET @counter = @counter + 1
      IF @counter >= 150
      BEGIN
         BREAK
      END
   END CATCH
END

SELECT * FROM #dateFormats;

参考:https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/