'SQL Server 2005: Determine datatype of variable

Is it possible to determine the type of a local variable at runtime in TSQL?

For example, say I wanted to do something along these lines:

IF ( @value IS INTEGER )

Or

IF ( TYPEOF(@value) = <whatever> )

Does anyone know of any way to accomplish this?

EDIT: This is not for a specific task, this is more of a general knowledge question. I do appreciate answers that indicate that the type should be known since it is declared within the same batch, I am curious as to whether the type can be determined at runtime.



Solution 1:[1]

using SQL 2019 , below code still working

DECLARE @MyVar int;SET @MyVar = 99;
DECLARE @MyVarDataType varchar(50);

SET @MyVarDataType  = cast(SQL_VARIANT_PROPERTY(@MyVar,'BaseType') AS varchar);

PRINT @MyVarDataType

Solution 2:[2]

I don't think so - BUT it is a local variable so are declaring it in the same procedure so you would know the type anyways - or am I missing something?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HO LI Pin
Solution 2 DJ.