从字符串转换日期和/或时间时转换失败

时间:2013-05-29 20:20:56

标签: sql sql-server tsql

我正在努力解决这个错误:从字符串转换日期和/或时间时转换失败。

从我的谷歌搜索来看,这是一个常见的错误,但到目前为止我没有尝试过任何工作。我已经尝试将@startdate转换为datetime和varchar而不管它,如下例所示。

我也尝试过对字段名称和参数名称使用convert,虽然不可否认,我可能只是错误地使用了语法。

ALTER PROCEDURE [dbo].[customFormReport]
(
    @formid int,
    @startdate DATETIME
)
AS
BEGIN
SET NOCOUNT ON

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(fieldname) from FormResponse WHERE FormID = @formid AND value IS NOT NULL FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT FormID, FormSubmissionID,' + @cols + ' from 
             (
                SELECT FormID, FormSubmissionID, fieldname, value
                FROM FormResponse WHERE FormID = ' + CAST(@formid AS VARCHAR(25)) + ' AND createDate > ' + @startdate + '
             ) x
            pivot 
            (
                max(value)
                for fieldname in (' + @cols + ')
            ) p '

execute(@query)

编辑:查询有效,除非我添加导致错误的位:

' AND createDate > ' + @startdate + '

2 个答案:

答案 0 :(得分:7)

问题是您正在尝试将datetime连接到varchar sql字符串。你需要转换它:

convert(varchar(10), @startdate, 120)

所以完整的代码将是:

ALTER PROCEDURE [dbo].[customFormReport]
(
    @formid int,
    @startdate DATETIME
)
AS
BEGIN
SET NOCOUNT ON

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(fieldname) from FormResponse WHERE FormID = @formid AND value IS NOT NULL FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT FormID, FormSubmissionID,' + @cols + ' from 
             (
                SELECT FormID, FormSubmissionID, fieldname, value
                FROM FormResponse 
                WHERE FormID = ' + CAST(@formid AS VARCHAR(25)) + ' 
                  AND createDate > ''' + convert(varchar(10), @startdate, 120) + '''
             ) x
            pivot 
            (
                max(value)
                for fieldname in (' + @cols + ')
            ) p '

execute(@query)

答案 1 :(得分:0)

当您动态构建SQL语句时,日期值需要用单引号括起来。每当构建动态语句时,请执行SELECT @query并确保结果看起来正确。

对于您的示例,您需要'WHERE createdate > ''' + covert(varchar(10), @startdate, 111) + '''

那将输出:WHERE createdate > '2013/05/29'

如果没有单引号,您将拥有:WHERE createdate > 2013/05/29