Search code examples
visual-studio-2010sql-server-2008-express

Creating SQL Server tables with formula


I want to create a database MyDatabase programmatically.

I want to create a table Table1 in that database, with some columns Columns1, Columns2, Columns3....

But some of my columns are having formula in it. And of course, my formula is based on other columns.

So suppose Column1 is having formula based on values of column2 and column3. And therefore not having any datatype defined.

So how to create tables with formula?


Solution

  • If you're talking about computed columns in SQL Server, then you just create them like this:

    CREATE TABLE dbo.OrderLine
    (OrderLineID INT IDENTITY(1,1) PRIMARY KEY,
     ProductID INT NOT NULL,   -- FK to Products table
     ItemPrice DECIMAL(16, 4),
     Quantity DECIMAL(10, 2),
     TotalPrice AS ItemPrice * Quantity   -- this is a computed column right here
    )