Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a "complicated" ComputedColumn in SQL Server?

SQL Server Beginner question:

I'm trying to introduce a computed column in SQL Server (2008). In the table designer of SQL Server Management Studio I can do this, but the designer only offers me one single edit cell to define the expression for this column. Since my computed column will be rather complicated (depending on several database fields and with some case differentiations) I'd like to have a more comfortable and maintainable way to enter the column definition (including line breaks for formatting and so on).

I've seen there is an option to define functions in SQL Server (scalar value or table value functions). Is it perhaps better to define such a function and use this function as the column specification? And what kind of function (scalar value, table value)?

To make a simplified example:

I have two database columns:

DateTime1 (smalldatetime, NULL)
DateTime2 (smalldatetime, NULL)

Now I want to define a computed column "Status" which can have four possible values. In Dummy language:

if (DateTime1 IS NULL and DateTime2 IS NULL)
    set Status = 0
else if (DateTime1 IS NULL and DateTime2 IS NOT NULL)
    set Status = 1
else if (DateTime1 IS NOT NULL and DateTime2 IS NULL)
    set Status = 2
else
    set Status = 3

Ideally I would like to have a function GetStatus() which can access the different column values of the table row which I want to compute the value of "Status" for, and then only define the computed column specification as GetStatus() without parameters.

Is that possible at all? Or what is the best way to work with "complicated" computed column definitions?

Thank you for tips in advance!

like image 249
Slauma Avatar asked Feb 17 '26 06:02

Slauma


1 Answers

You can always also use a user-defined function for this - wrap your "complicated" code into an UDF, and use that to define your computed column:

CREATE FUNCTION dbo.GetStatus(@DateTime1 DATETIME, @DateTime2 DATETIME)
RETURNS INT
AS BEGIN
    DECLARE @Result INT

    IF (@DateTime1 IS NULL AND @DateTime2 IS NULL)
       SET @Result = 0
    ELSE IF (@DateTime1 IS NULL AND @DateTime2 IS NOT NULL)
       SET @Result = 1
    ELSE IF (@DateTime1 IS NOT NULL AND @DateTime2 IS NULL)
       SET @Result = 2
    ELSE
       SET @Result = 3

    RETURN @Result
END

and then you define your computed column as:

ALTER TABLE dbo.YourTable
    ADD Status AS dbo.GetStatus(DateTime1, DateTime2)
like image 184
marc_s Avatar answered Feb 19 '26 20:02

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!