Search code examples
sqlsql-serversql-server-2000

SQL Create Table [Default]


Can I specify DEFAULT to get the exact value of a column?

I am creating a Serial table, with range, some has From and To and some are just singular.

Therefore I have two columns: [Serial_Fr] & [Serial_To]

If I insert Serial_Fr only, I want to populate Serial_To = Serial_Fr.

How do I do that? Or should I use triggers and just set default = '', in doing this I think it will cause a strain when I have millions of serials.


Solution

  • Create a View which is

    CREATE VIEW MyView AS
    SELECT 
      Serial_Fr,
      Serial_To =  COALESCE(Serial_To,Serial_Fr)
    FROM MyTable
    

    Or this could be done in a Stored Procedure

    But what is wrong with leaving some of the entries in Serial_To as NULL ?


    Edit

    ISNULL is T-sql : COALESCE is 92 standard sql. There is a good discussion of the subtle differences between these functions HERE ON SO

    Martin Smith also refers to an article which has this interesting example that illustrates a difference:

    DECLARE @test VARCHAR(2)
    DECLARE @first VARCHAR(4)
    DECLARE @second VARCHAR(4)
    
    SELECT @first = ISNULL(@test, 'test')
    SELECT @second = COALESCE(@test, 'test')
    
    PRINT @first
    PRINT @second