SQL Server 2005:确定变量的数据类型

时间:2021-02-17 23:39:35

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

是否可以在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.

编辑:这不是一个特定的任务,这是一个普遍的知识问题。我很欣赏那些表明类型应该被知道的答案,因为它是在同一批中声明的,我很好奇是否可以在运行时确定类型。

2 个解决方案

#1


27  

run this

运行这个

declare @d int

select @d = 500

if cast(sql_variant_property(@d,'BaseType') as varchar(20))  = 'int'
print 'yes'
else
print 'no'

#2


-1  

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?

我不这么认为,但它是一个局部变量所以在相同的过程中声明它这样你就可以知道类型了,还是我漏掉了什么?

#1


27  

run this

运行这个

declare @d int

select @d = 500

if cast(sql_variant_property(@d,'BaseType') as varchar(20))  = 'int'
print 'yes'
else
print 'no'

#2


-1  

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?

我不这么认为,但它是一个局部变量所以在相同的过程中声明它这样你就可以知道类型了,还是我漏掉了什么?