Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User-Defined Table Type insertion sometimes causing conversion error

I have a User-Defined Table Type called 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):

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.

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

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.

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.

like image 819
theChrisKent Avatar asked May 23 '11 02:05

theChrisKent


People also ask

How do you change the user-defined table type?

The user-defined table type definition cannot be modified after it is created. You will need to drop any procedures or functions which depend on the type; drop the type; create the type with the new definition; and finally re-create the dependant procedures / functions.

How to CREATE a user-defined data type in SQL?

To create a user-defined data type. In Object Explorer, expand Databases, expand a database, expand Programmability, expand Types, right-click User-Defined Data Types, and then click New User-Defined Data Type.


1 Answers

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.

Try to cast @Name and @Phone to varchar

INSERT INTO @AuditColumns (ColumnName,NewValue)
SELECT  'Name', cast(@Name as varchar) UNION ALL
SELECT  'Phone', cast(@Phone as varchar)
like image 168
dance2die Avatar answered Sep 25 '22 16:09

dance2die