簡體   English   中英

為什么在使用isNull時收到此錯誤消息

[英]Why am I getting this error message when using isNull

我有這個更新觸發器,除了新的和舊的值相同時,它都會記錄列之外,它也起作用。 (發生這種情況是由於EntityFramework更新語句的方式)。

set nocount on;
    create table #updatedCols (Id int identity(1, 1), updateCol nvarchar(200))

    --find all columns that were updated and write them to temp table
    insert into #updatedCols (updateCol)
    select
        column_name
    from
        information_schema.columns
    where   
        table_name = 'Items'   
        and convert(varbinary, reverse(columns_updated())) & power(convert(bigint, 2), ordinal_position - 1) > 0

    --temp tables are used because inserted and deleted tables are not available in dynamic SQL
    select * into #tempInserted from inserted
    select * into #tempDeleted from deleted

    declare @cnt int = 1
    declare @rowCnt int
    declare @columnName varchar(1000)
    declare @sql nvarchar(4000)

    select @rowCnt = count(*) from #updatedCols

    --execute insert statement for each updated column
    while @cnt <= @rowCnt
    begin
        select @columnName = updateCol from #updatedCols where id = @cnt

        set @sql = N'
            insert into [Events] ([RecordId], [EventTypeId], [EventDate], [ColumnName], [OriginalValue], [NewValue], [TenantId], [AppUserId], [TableName])
            select
                i.Id, 2, GetUTCDate(), ''' + @columnName + ''', d.' + @columnName + ', i.' + @columnName +', i.TenantId, i.UpdatedBy, ''Item''
            from
                #tempInserted i
                join #tempDeleted d on i.Id = d.Id

            '
        exec sp_executesql @sql
        set @cnt = @cnt + 1
    end

因此,我添加了更新的聯接以過濾出值相同的位置:

 #tempDeleted d on i.Id = d.Id and isnull(i.' + @columnName + ', '''') <> isnull(d.' +@columnName + ', '''')

但是,我現在收到錯誤: SqlException: Error converting data type varchar to numeric.

我猜想在某些情況下,舊值是null(因此將其轉換為空字符串),而新值是int,因此Sql Server嘗試將varchar轉換為int以便將它們與錯誤進行比較被拋出。

這個對嗎? 如果是這樣,我該如何解決?

如果您不想參數化變量,請執行以下操作

isnull(i.' + convert(varchar(100),@columnName) + ', '''')

否則使用參數定義選項

https://docs.microsoft.com/zh-cn/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-2017

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM