简体   繁体   中英

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.

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. 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.

You can use SQL_VARIANT_PROPERTY() to determine the computed column's base data type:

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

As Martin has correctly pointed out, the above method will not work if the table is empty.

You could add some arbitrary row and apply the method, or use the alternative way suggested by Martin, which works regardless of data presence:

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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