用户定义的表类型插入有时会导致转换错误

时间:2022-08-28 12:56:00

I have a User-Defined Table Type called tvpInsertedColumns:

我有一个名为tvpInsertedColumns的用户定义表类型:

CREATE TYPE [Audit].[tvpInsertedColumns] AS TABLE(
    [ColumnName] [varchar](max) NOT NULL,
    [NewValue] [varchar](max) NULL
)

In a Stored Procedure I am attempting to do this (Both @Name and @Phone are VARCHARs):

在存储过程中我试图这样做(@Name和@Phone都是VARCHAR):

DECLARE @AuditColumns Audit.tvpInsertedColumns
INSERT INTO @AuditColumns (ColumnName,NewValue)
    SELECT  'Name',@Name UNION ALL
    SELECT  'Phone',@Phone

This fails with the error:

这失败并出现错误:

Conversion failed when converting the varchar value 'Some Name' to data type int.

将varchar值'Some Name'转换为数据类型int时转换失败。

However, in another Stored Procedure I am doing this (@AddressLine1 and @AddressLine1 are VARCHARs):

但是,在另一个存储过程中我这样做(@ AddressLine1和@ AddressLine1是VARCHAR):

DECLARE @AuditColumns AS Audit.tvpInsertedColumns
INSERT INTO @AuditColumns (ColumnName,NewValue)
    SELECT  'AddressLine1',@AddressLine1 UNION ALL
    SELECT  'AddressLine2',@AddressLine2

And everything works just fine.

一切正常。

Both Stored Procedures are just doing a simple insert and then trying to use the type along with another stored procedure that takes the UDT as a parameter.

两个存储过程都只是执行一个简单的插入,然后尝试将该类型与另一个以UDT作为参数的存储过程一起使用。

This is my first real experience with UDTs, so I hope I'm just missing something obvious, but this makes no sense to me. Let me know if you need further information.

这是我对UDT的第一次真实体验,所以我希望我只是遗漏了一些明显的东西,但这对我来说毫无意义。如果您需要更多信息,请与我们联系。

1 个解决方案

#1


11  

DECLARE @AuditColumns Audit.tvpInsertedColumns
INSERT INTO @AuditColumns (ColumnName,NewValue)
SELECT  'Name',@Name UNION ALL
SELECT  'Phone',@Phone

I don't know much about UDTs but what I think is happening is that, at one point, either @name or @phone values are of type integer.

我对UDT了解不多,但我认为正在发生的事情是,@ name或@phone值一直是整数类型。

Try to cast @Name and @Phone to varchar

尝试将@Name和@Phone转换为varchar

INSERT INTO @AuditColumns (ColumnName,NewValue)
SELECT  'Name', cast(@Name as varchar) UNION ALL
SELECT  'Phone', cast(@Phone as varchar)

#1


11  

DECLARE @AuditColumns Audit.tvpInsertedColumns
INSERT INTO @AuditColumns (ColumnName,NewValue)
SELECT  'Name',@Name UNION ALL
SELECT  'Phone',@Phone

I don't know much about UDTs but what I think is happening is that, at one point, either @name or @phone values are of type integer.

我对UDT了解不多,但我认为正在发生的事情是,@ name或@phone值一直是整数类型。

Try to cast @Name and @Phone to varchar

尝试将@Name和@Phone转换为varchar

INSERT INTO @AuditColumns (ColumnName,NewValue)
SELECT  'Name', cast(@Name as varchar) UNION ALL
SELECT  'Phone', cast(@Phone as varchar)