简体   繁体   English

如何在存储过程中定义计算列

[英]How can I define a computed column in a stored procedure

I have question about using computed columns in stored procedures. 我对在存储过程中使用计算列有疑问。

I already have some fields in my table as computed columns. 我的表中已经有一些字段作为计算列。

Now I have to create stored procedure and this SP should read the value in computed column to make some operation. 现在,我必须创建存储过程,并且此SP应该读取计算列中的值以进行一些操作。

I already create my procedure with some cursor but when I'm trying to execute it, I have error ralted with data type for computed column (as you know there is no data type for computed column), so how can I process that. 我已经使用一些游标创建了过程,但是当我尝试执行它时,由于计算列的数据类型出现错误(由于您知道计算列没有数据类型),因此如何进行处理。

Computed columns do have a data type, it's just implicitly determined (if that's the phrase) from the data is based on. 计算列的确具有数据类型,它只是根据数据所基于的隐式确定的(如果是这样的话)。 So if you have 所以如果你有

ColA int
ColB int 

and a calculated column based on ColA + ColB, the calculated column will also be an int. 以及基于ColA + ColB的计算列,该计算列也将是一个int。 So, you need to (1) figure out the datatype of the result of your calculated column's forumla, (2) modify your code to properly account for that data type, and (3) like Mitch Wheat says, rewrite it to not use a cursor. 因此,您需要(1)找出计算列的论坛结果的数据类型,(2)修改代码以正确考虑该数据类型,以及(3)如Mitch Wheat所说,将其重写为不使用光标。

You can use SQL_VARIANT_PROPERTY() to determine the computed column's base data type: 您可以使用SQL_VARIANT_PROPERTY()确定计算列的基础数据类型:

SELECT TOP 1 SQL_VARIANT_PROPERTY(ComputedColumnName, 'BaseType') FROM TableName

Or, if you like: 或者,如果您喜欢:

SELECT DISTINCT SQL_VARIANT_PROPERTY(ComputedColumnName, 'BaseType') FROM TableName

I understand this should be done once so you can specify the correct type of the parameter. 我知道应该执行一次,这样您才能指定正确的参数类型。 But if you need, you can also use the function in your scripts. 但是,如果需要,也可以在脚本中使用该函数。


UPDATE UPDATE

As Martin has correctly pointed out, the above method will not work if the table is empty. 正如Martin正确指出的,如果表为空,则上述方法将不起作用。

You could add some arbitrary row and apply the method, or use the alternative way suggested by Martin, which works regardless of data presence: 您可以添加任意行并应用该方法,也可以使用Martin建议的替代方法,无论数据存在与否,该方法都可以起作用:

select t.name,t.precision,t.scale,t.max_length, t.is_nullable
from sys.computed_columns c
   join sys.types t on t.user_type_id = c.user_type_id
where c.name='col_name' and c.object_id=object_id('schema_name.table_name')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM