简体   繁体   中英

Best way to lookup the default value of a column in Sql Server

I want to lookup the default value of a column in my SQL2005 database. I only have the SQL server connection string, so I can only use the Sql library namespace (can't use the Oledb GetSchema stuff). I know there is a GetSchema()... but how do I use it to get a column schema, and thus the default value? I can't fillSchema on a datatable, because that doesn't appear to fill the default value property. I can use "exec sp_columns 'ADDRESS_MASTER'" and that returns default values, but they are not in a clean format... for example, one of my text column default comes back as "(N'test)".

I also want to get column size... sp_columns seems to give me everything... but I don't know how to decode the default values in all cases?

Good question. If the datatype is known ahead of time, you could use some obvious string replacement operations to get the formatted value. For example, if 1 is the default value of an int column, it is returned in the sp_columns column_def result as ((1)). I've worked on this problem for a while this evening and I have no better advice.

I'm not sure if it would be helpful to anyone else who wants to take a crack at this, but here's the sp_columns call along with captured results:

Declare @TableName varchar(255); 
Set @TableName = 'Table';

Declare @ColumnName varchar(255); 
Set @ColumnName = 'Column';

Declare @ColumnDefinition Table 
(
    TABLE_QUALIFIER  sysname null,
    TABLE_OWNER      sysname null,
    TABLE_NAME       sysname null,
    COLUMN_NAME      sysname null,
    DATA_TYPE        sysname null,
    TYPE_NAME        sysname null,
    PRECISION        int null, 
    LENGTH           int null,
    SCALE            int null,
    RADIX            int null,
    NULLABLE         bit null,
    REMARKS          nvarchar(4000) Null,
    COLUMN_DEF       sysname  null,
    SQL_DATA_TYPE    int null,
    SQL_DATETIME_SUB int null,
    CHAR_OCTET_LENGTH int null,
    ORDINAL_POSITION  int null,
    IS_NULLABLE       char(3) null,
    SS_DATA_TYPE      int null
)

Insert Into @ColumnDefinition
Exec sp_columns @TableName, @column_name = @ColumnName

Select COLUMN_DEF From @ColumnDefinition

Your problem here is the default value is an expression and it seems like you want it to just return a value such as 'bob' or 5.

This pretty much falls over the moment you have GetDate() or call a custom function such as dbo.MyFunc(). At this point what should it return as the default value?

As such the only reliable thing the sql server can do is return to you the expression it will use to generate the default value, you could run this through the sql server again to determine the result, ie:

DECLARE @def nvarchar(max)

SELECT @def = column_def FROM information_schema.columns
WHERE table_name = 'ADDRESS' AND column_name = 'ADDRESS_MASTER'

EXEC ('SELECT ' + @def)

Of course, if the expression isn't constant such as in the case of GetDate this will be incorrect by the time you come to insert actual data. Also it would cause problems if using a custom function with side-effects, but a custom function with side-effects used in a default I'd consider a problem already.

Take a look at the output of

select * from INFORMATION_SCHEMA.Columns

Does that help?

You could use the SMO (SQL Server Management Objects) to retrieve that information. You'll need to add references to some of the Microsoft.SqlServer.* assemblies (not sure which ones - it's rather confusing), and then you should be able to do something like this:

Server myServer = new Server("servername");
Database myDatabase = myServer.Databases["myDatabaseName"];
Table myTable = myDatabase.Tables["myTableName"];
Column myColumn = myTable.Columns["myColumnName"];

string defaultValue = myColumn.Default;

Marc

To get the default constraint value for a particular column, do this :

SELECT defaults.definition
FROM sys.all_columns AS cols
INNER JOIN sys.default_constraints AS defaults ON cols.default_object_id = defaults.object_id
WHERE cols.object_id = @TABLEID AND cols.[name] = @COLNAME

where @TABLEID is just the ID of the table and @COLNAME the name of the column you want in the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM