0

SQL Server 2008 中的以下存储过程引发错误

/****** Object:  StoredProcedure [dbo].[UpdateCPA]    ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[pdateCPA_INT]
    @CPAColumn_Name nvarchar(100), @value Int, @RecordNum nvarchar(100)
AS
BEGIN
    SET NOCOUNT ON;
    --declare @CPAColumn_Name nvarchar(100) = 'UsrsID'
    --declare @value Int = 3575
    --declare @RecordNum int = 1

    declare @thedate smalldatetime
    set @thedate = GETDATE()
    --select @thedate as NOW

    declare @cmd nvarchar(max)

    set @cmd = 'Update tblTimeCPAReport 
    set ' + @CPAColumn_Name + ' = '+@value+' 
    set ReportLastUpdate = ' + @thedate + '
    where RecordNum='+@RecordNum

    exec sp_executesql @cmd
    select @cmd
END

它抛出这个错误

将 nvarchar 值 'Update tblTimeCPAReport set UsrsID = ' 转换为数据类型 int 时转换失败。

4

3 回答 3

1

每当服务器看到 a+时,它都会检查双方的类型,如果它们不同,则必须执行转换。

因为' = '+@value+',在左边,我们在右边有一个字符串 ( nvarchar(max)) int。它决定将字符串转换为int.

为防止这种情况,请自行将其转换int为字符串:' = '+CONVERT(nvarchar(10),@value)+'

于 2012-10-29T14:12:13.643 回答
1

您需要参数-- cast()intcast(@value as nvarchar(100))

/****** Object:  StoredProcedure [dbo].[UpdateCPA]    ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[pdateCPA_INT]
    @CPAColumn_Name nvarchar(100), @value Int, @RecordNum nvarchar(100)
AS
BEGIN
    SET NOCOUNT ON;
    --declare @CPAColumn_Name nvarchar(100) = 'UsrsID'
    --declare @value Int = 3575
    --declare @RecordNum int = 1

    declare @thedate smalldatetime
    set @thedate = GETDATE()
    --select @thedate as NOW

    declare @cmd nvarchar(max)

    set @cmd = 'Update tblTimeCPAReport 
    set ' + @CPAColumn_Name + ' = '''+cast(@value as nvarchar(100))+''' 
       ,  ReportLastUpdate = ''' + convert(nvarchar(25), @thedate, 120) + '''
    where RecordNum='''+@RecordNum+''''

    exec sp_executesql @cmd
    select @cmd
END

由于您@cmd是数据类型,因此使用的nvarchar(max)所有参数都需要相似,包括:

@value  -- use cast(@value as nvarchar(100))
@thedate --- use convert(nvarchar(25), @thedate, 120)
于 2012-10-29T14:13:05.780 回答
1

1)您应该将 @value 转换为 varchar

2)第二个“set”会导致错误,propt 语法是SET <col> = <values> [, <col> = Value>, …]

3) 将 @thedate 转换为 varchar,并将其括在引号中

4) 如果@Recordnum 是字符串,也要加上引号,否则很好

使用以上所有内容,以下内容:

set @cmd = 'Update tblTimeCPAReport 
set ' + @CPAColumn_Name + ' = ''' + cast(@value as varchar(10)) + '''
set ReportLastUpdate = ''' + convert(varchar(50), @thedate, 109) + '''
where RecordNum = ''' + @RecordNum + ''''

应该产生一个字符串,如:

Update tblTimeCPAReport 
 set <CPAColumn_Name> = <@value>
  ,ReportLastUpdate = '<@thedate>'
 where RecordNum = '<@RecordNum>'

(如果 @RecordNum 包含数值,则将引号括起来)

于 2012-10-29T14:21:01.287 回答