views:

40

answers:

2

How can I find out the default value of a column in a table using a SQL query?

Using the sp:

sp_columns @tablename 

I get some info on the columns of a particular table but the default value of the columns is missing, How can I get it?

+2  A: 
SELECT object_definition(default_object_id) AS definition
FROM   sys.columns
WHERE  name      ='colname'
AND    object_id = object_id('tablename')
Martin Smith
It did for me. Obviously it only returns something if the column actually has a default defined.
Martin Smith
Oh crap, I was supposed to overwrite "colname" and "tablename", that's why it didn't work when I tested... Sorry about that.
OMG Ponies
@OMG - No worries!
Martin Smith
+2  A: 

Use:

   SELECT so.name AS table_name, 
          sc.name AS column_name, 
          sm.text AS default_value
     FROM sys.sysobjects so
     JOIN sys.syscolumns sc ON sc.id = so.id
LEFT JOIN sys.syscomments SM ON sm.id = sc.cdefault
    WHERE so.xtype = 'U' 
      AND SO.name = @yourtable
 ORDER BY so.[name], sc.colid
OMG Ponies