2

我正在努力处理返回错误的查询:从字符串转换日期和/或时间时转换失败。

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

我也尝试过对字段名和参数名使用转换,尽管不可否认,我可能只是语法错误。

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 + '
4

2 回答 2

7

问题是您试图将 a 连接datetime到您的varcharsql 字符串。你需要转换它:

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)
于 2013-05-29T20:22:57.193 回答
0

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

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

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

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

于 2013-05-29T20:55:45.350 回答