简体   繁体   English

在Sql Server中查找列的默认值的最佳方法

[英]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. 我想在SQL2005数据库中查找列的默认值。 I only have the SQL server connection string, so I can only use the Sql library namespace (can't use the Oledb GetSchema stuff). 我只有SQL服务器连接字符串,所以我只能使用Sql库命名空间(不能使用Oledb GetSchema的东西)。 I know there is a GetSchema()... but how do I use it to get a column schema, and thus the default value? 我知道有一个GetSchema()...但是如何使用它来获取列模式,从而得到默认值? 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)". 我可以使用“exec sp_columns'ADDRESS_MASTER'”并返回默认值,但它们不是一个干净的格式...例如,我的一个文本列默认返回为“(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? 我也想获得列大小... sp_columns似乎给了我一切......但我不知道如何在所有情况下解码默认值?

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)). 例如,如果1是int列的默认值,则在sp_columns column_def结果中将其返回为((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: 我不确定是否对其他想要解决此问题的人有所帮助,但这里是sp_columns调用以及捕获的结果:

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. 这里你的问题是默认值是一个表达式,似乎你希望它只返回一个值,如'bob'或5。

This pretty much falls over the moment you have GetDate() or call a custom function such as dbo.MyFunc(). 当你有GetDate()或调用自定义函数(如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: 因此,sql server可以做的唯一可靠的事情就是返回它将用于生成默认值的表达式,您可以再次通过sql server运行它来确定结果,即:

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. 当然,如果表达式不是常量,例如在GetDate的情况下,那么在您插入实际数据时这将是不正确的。 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. 您可以使用SMO(SQL Server管理对象)来检索该信息。 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: 您需要添加一些Microsoft.SqlServer.*程序集的引用(不确定哪些 - 它相当混乱),然后您应该能够执行以下操作:

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. 其中@TABLEID只是表的ID,而@COLNAME是数据库中所需列的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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