Reputation: 23
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.
Upvotes: 0
Views: 1293
Reputation: 77657
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')
Upvotes: 1
Reputation: 40309
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.
Upvotes: 4