In this article, we will demonstrate T-SQL metadata functions available in the SQL Server.

在本文中,我们将演示SQL Server中可用的T-SQL元数据功能。

介绍 (Introduction)

Before we jump into the specifics of metadata functions in SQL Server, let’s quickly understand how exactly term metadata is beneficial for us.

在深入介绍SQL Server中元数据功能的细节之前,让我们快速了解一下元数据到底对我们有何好处。

Metadata, as most of you may already know, provides the basic and relevant information about the data. Metadata functions in SQL Server return information about the database, database objects, database files, file groups etc. in SQL Server. Instead of writing complex queries to seek database information, SQL professionals can make use of T-SQL metadata functions to retrieve database info, which helps them to save a great amount of time and effort.

众所周知,元数据提供了有关数据的基本和相关信息。 SQL Server中的元数据功能返回有关SQL Server中的数据库,数据库对象,数据库文件,文件组等的信息。 SQL专业人员无需编写复杂的查询来查找数据库信息,而是可以使用T-SQL元数据功能来检索数据库信息,这有助于他们节省大量时间和精力。

Additionally, they become extremely handy and useful in tracking and monitoring databases when they are used along with the system views. In case you are not familiar with the system views, I would recommend you to refer to this article, Discovering SQL server instance information using system views to learn about them.

此外,当它们与系统视图一起使用时,它们在跟踪和监视数据库时变得非常方便并且很有用。 如果您不熟悉系统视图,建议您参考本文“ 使用系统视图发现SQL服务器实例信息”以了解它们。

准备我们的环境 (Preparing our environment)

We will need SQL Server, SSMS and a SQL database to understand Metadata functions in SQL Server. Since SQL Server 2019 is not released yet and is in RC, we will run the queries against SQL Server 2017. For SSMS, we will be using the latest version v18.1, in case you don’t’ have it, you can get it from here. For the sake of brevity, I will be referring to the sample database – AdventureWorksDW2017 in this article, you can download it from here

我们将需要SQL Server,SSMS和SQL数据库来了解SQL Server中的元数据功能。 由于SQL Server 2019尚未发布且处于RC中,因此我们将针对SQL Server 2017运行查询。对于SSMS,我们将使用最新版本v18.1,以防万一,您可以获得从这里来 。 为了简洁起见,我将在本文中引用示例数据库– AdventureWorksDW2017 ,您可以从此处下载它

T-SQL metadata functions in SQL Server come under the umbrella of System functions in SSMS and can be accessed as shown below. Expand Databases, and navigate to Programmability in database AdventureWorksDW2017. Double-click Functions and System Functions and expand Metadata Functions to see the complete list of metadata functions under it.

SQL Server中的T-SQL元数据功能属于SSMS中的系统功能的保护范围,可以按如下所示进行访问。 展开数据库 ,然后导航到数据库AdventureWorksDW2017中的可编程性 。 双击“ 功能系统功能”,然后展开“ 元数据 功能”以查看其下的元数据功能的完整列表。

And below is the extended list of metadata functions:

以下是元数据功能的扩展列表:

I have classified these T-SQL metadata functions in several categories as shown below, and tried to add almost all metadata functions in this consolidated list. You can consider this as a single go-to place to refer to these functions in SQL Server.

我将这些T-SQL元数据功能分为以下几类,并尝试将几乎所有元数据功能添加到此合并列表中。 您可以将其视为在SQL Server中引用这些功能的唯一参考。

It will be difficult for me to cover each one of them in a single article, so I will try to demonstrate the majority of them in the following broad categories:

我很难在一篇文章中涵盖其中的每一个,因此我将尝试在以下广义类别中展示其中的大多数:

  1. Object IDs – OBJECT_ID(), DB_ID(), File_ID() etc.对象ID – OBJECT_ID(),DB_ID(),File_ID()等。
  2. Object Names – OBJECT_NAME(), DB_NAME(), COL_NAME() etc.对象名称– OBJECT_NAME(),DB_NAME(),COL_NAME()等。
  3. Object Property values – OBJECTPROPERTY(), DATABASEPROPERTY(), INDEXPROPERTY() etc.对象属性值– OBJECTPROPERTY(),DATABASEPROPERTY(),INDEXPROPERTY()等。
  4. Other metadata functions like @@procid, parsename(), applock_test() etc.其他元数据功能,例如@@ procid,parsename(),applock_test()等。

Let’s go ahead and learn about these functions in detail. We will cover the basic definition, syntax, a few examples, output and any special feature associated with these functions.

让我们继续详细了解这些功能。 我们将介绍基本定义,语法,一些示例,输出以及与这些功能相关的任何特殊功能。

返回对象ID的函数 (Functions returning Object IDs)

T-SQL OBJECT_ID()元数据函数 (T-SQL OBJECT_ID() metadata function)

This function returns the database object ID number of a schema object and returns NULL on error. These objects can be tables, views, constraints or stored procedures etc.

此函数返回架构对象的数据库对象ID号,并在错误时返回NULL。 这些对象可以是表,视图,约束或存储过程等。

函数OBJECT_ID()的语法 (Syntax of function OBJECT_ID())

OBJECT_ID ( ‘database_name . schema_name . object_name’ )

OBJECT_ID('数据库名称。模式名称。对象名称')

The syntax of this function is self-explanatory.

此函数的语法不言自明。

函数OBJECT_ID()的示例 (Examples of function OBJECT_ID())

  1. Execute the code below to retrieve Object Id of the table DimEmployee in the database AdventureWorksDW2017 using this function

    执行以下代码,使用此函数在数据库AdventureWorksDW2017中检索表DimEmployee的对象ID。

    SELECT OBJECT_ID('AdventureWorksDW2017.dbo.DimEmployee') AS 'Object Id'
    
  2. If the current database context is AdventureWorksDW2017, you can drop database name from the syntax of the function Object_Id() and use it like the below. Alternatively, you can execute the above code using this ‘USE AdventureWorksDW2017’, it will make sure you are pointing to the right database

    如果当前数据库上下文为AdventureWorksDW2017,则可以从函数Object_Id()的语法中删除数据库名称,并按如下所示使用它。 或者,您可以使用此“ USE AdventureWorksDW2017”执行以上代码,这将确保您指向正确的数据库

    SELECT OBJECT_ID('dbo.DimEmployee') AS 'Object Id'
    

    The Object ID value returned by OBJECT_ID() function is stored in the sys.objects view in the column object_id. One such example is shown below, it helps to retrieve information like the name (DimEmployee), object_id, type (U= user-defined table) etc from this

    OBJECT_ID()函数返回的对象ID值存储在sys.objects视图的object_id列中。 下面显示了一个这样的示例,它有助于从中检索名称(DimEmployee),object_id,类型(U =用户定义的表)等信息。

    SELECT * FROM sys.objects WHERE object_id = 1077578877
    
  3. Metadata function OBJECT_ID() is also useful in verifying the existence of objects in the database. And based on if the object exists, we can take further action, very common action is to drop the table

    元数据函数OBJECT_ID()在验证数据库中是否存在对象时也很有用。 根据对象是否存在,我们可以采取进一步的措施,非常常见的措施是删除表

  4. One major use of metadata function, OBJECT_ID() is to verify the existence of objects, like tables in the database. In the below example, this function checks if the table ‘DimEmployee’ exists in the database AdventureWorksDW2017, if yes, it renames the column ‘Title’ to ‘Title Name’

    元数据函数OBJECT_ID()的一项主要用途是验证对象的存在,例如数据库中的表。 在下面的示例中,此函数检查AdventureWorksDW2017数据库中是否存在表“ DimEmployee”,如果是,则将“标题”列重命名为“标题名称”

    USE AdventureWorksDW2017;
    GO
    IF OBJECT_ID (N'dbo.DimEmployee', N'U') IS NOT NULL
    EXEC sp_rename 'DimEmployee.Title', 'Title Name', 'COLUMN'
    

T-SQL DB_ID()元数据函数 (T-SQL DB_ID() metadata function)

As the name suggests, this function returns the ID of the specified database. When you create a database in SSMS, a new record is inserted into both sys.databases and sys.sysdatabases table with a brand new Id and other relevant information like version, filename etc. There is a metadata function, DB_ID() that helps to retrieve this number.

顾名思义,此函数返回指定数据库的ID。 当您在SSMS中创建数据库时,会将带有新ID和其他相关信息(如版本,文件名等)的新记录插入sys.databases和sys.sysdatabases表中。元数据函数DB_ID()有助于检索此号码。

函数DB_ID的语法() (Syntax of function DB_ID ())

DB_ID ( [ ‘database_name’ ] )

DB_ID(['database_name'])

To retrieve id value, database name is passed . Unlike function OBJECT_ID(), this can be executed without passing arguments in it, in that case, it will return database identification (ID) number of the current database.

要检索id值,将传递数据库名称。 与函数OBJECT_ID()不同,它可以在不传递参数的情况下执行,在这种情况下,它将返回当前数据库的数据库标识(ID)号。

函数示例DB_ID() (Examples of function DB_ID())

  1. Execute the below examples to see how this function works. The first three queries return the database id for system databases – master, tempdb and msdb. In the last line of code, this function is passed without any argument and it returns Id =5 for the current database AdventureWorksDW2017

    执行以下示例以查看此功能的工作原理。 前三个查询返回系统数据库的数据库ID-master,tempdb和msdb。 在代码的最后一行中,此函数不带任何参数地传递,并且它为当前数据库AdventureWorksDW2017返回Id = 5

    SELECT DB_ID('master') 'master DBId'
    SELECT DB_ID('tempdb') 'tempdb DBId'
    SELECT DB_ID('msdb') 'msdb DBId'
    SELECT DB_ID() 'Current DBId'
    
  2. This function helps to narrow down the data when used along with system views and dynamic management views as shown below

    与系统视图和动态管理视图一起使用时,此功能有助于缩小数据范围,如下所示

    SELECT name,database_id, create_date, collation_name, compatibility_level FROM sys.databases WHERE database_id = DB_ID();

    从sys.database中选择名称,数据库ID,创建日期,排序规则名称,兼容性级别WHERE database_id = DB_ID();

    Exercise # 1 – Execute the below query and see if for yourself how results are reduced from 321 to 56 on passing function DB_ID() as a parameter in the DMV sys.dm_db_index_physical_stats

    练习1 –执行以下查询,并亲自查看将函数DB_ID()作为DMV sys.dm_db_index_physical_stats中的参数传递时,结果如何从321减少到56

    SELECT * FROM sys.dm_db_index_physical_stats (DB_ID(),NULL, NULL, NULL, NULL);
    

T-SQL FILE_ID()/ FILE_IDEX()元数据功能 (T-SQL FILE_ID()/ FILE_IDEX() metadata function)

As a database professional, I have often dealt with files like primary data files (.mdf), secondary data files (.ndf) , log files (.ldf) and filegroups in SQL Server. Function FILE_ID() is a deprecated feature for SQL Server 2017 and FILE_IDEX() is it’s replacement. This function returns the identification number associated with a database file of the current database.

作为数据库专业人员,我经常在SQL Server中处理诸如主数据文件(.mdf),辅助数据文件(.ndf),日志文件(.ldf)和文件组之类的文件。 函数FILE_ID()是SQL Server 2017中不推荐使用的功能,而FILE_IDEX()是它的替代功能。 此函数返回与当前数据库的数据库文件关联的标识号。

函数FILE_IDEX()的语法 (Syntax of function FILE_IDEX())

FILE_IDEX ( file_name )

FILE_IDEX(file_name)

Where, file_name is the name of the logical database file and it returns type int.

其中,file_name是逻辑数据库文件的名称,它返回int类型。

函数FILE_IDEX()的示例 (Examples of function FILE_IDEX())

Catalog view, sys.database_files contains information of current database file names. From this table, we can retrieve the name of the file and pass it in the FILE_IDEX() to obtain File ID.

目录视图sys.database_files包含当前数据库文件名的信息。 从该表中,我们可以检索文件的名称,并将其传递到FILE_IDEX()中以获得文件ID。

SELECT * FROM sys.database_files
SELECT FILE_IDEX('AdventureWorksDW2017') AS FileID
SELECT FILE_IDEX('AdventureWorksDW2017_log') AS FileID

T-SQL SCHEMA_ID()元数据功能 (T-SQL SCHEMA_ID() metadata function)

As the name suggests, it returns the schema id of the schema name.

顾名思义,它返回模式名称的模式ID。

函数SCHEMA_ID()的语法 (Syntax of function SCHEMA_ID())

SCHEMA_ID ( [ schema_name ] )

SCHEMA_ID([schema_name])

Which means we can obtain schema id of an object by passing the schema name as an argument in it.

这意味着我们可以通过将模式名称作为参数传递给它来获取对象的模式ID。

函数SCHEMA_ID()的示例 (Examples of function SCHEMA_ID())

The following first two examples return schema Id of default schema and system schema respectively using SCHEMA_ID(). The subsequent example helps to retrieve information from the system catalog view, sys.objects for the ‘dbo’ schema and scalar functions.

以下前两个示例分别使用SCHEMA_ID()返回默认模式和系统模式的模式ID。 下一个示例有助于从系统目录视图,“ dbo”模式的sys.objects和标量函数中检索信息。

SELECT SCHEMA_ID() AS DefaultSchemaId
SELECT SCHEMA_ID('sys') AS SystemSchemaId  SELECT name, schema_id, type_desc,* FROM sys.objects WHERE schema_id = SCHEMA_ID('dbo') AND type = 'FN';
SELECT name, schema_id, type FROM sys.objects WHERE schema_id = SCHEMA_ID('sys');

T-SQL FILEGROUP_ID()元数据函数 (T-SQL FILEGROUP_ID() metadata function)

SQL Server organizes data files in the collection named File Groups and there are several file group functions that helps DBA in their tasks. The function FILEGROUP_ID() returns the file ID for the corresponding file group name.

SQL Server在名为“文件组”的集合中组织数据文件,并且有几个文件组功能可帮助DBA执行任务。 函数FILEGROUP_ID()返回相应文件组名称的文件ID。

函数FILEGROUP_ID()的语法 (Syntax of function FILEGROUP_ID())

FILEGROUP_ID ( ‘filegroup_name’ )

FILEGROUP_ID('filegroup_name')

Where filegroup_name represents the filegroup name for which filegroup id is returned.

其中,filegroup_name代表为其返回文件组ID的文件组名称。

函数FILEGROUP_ID()的示例 (Examples of function FILEGROUP_ID())

I have created a filegroup named, DemoFileGroup to demonstrate how this function works. You can check the system view, sys.sysfilegroups to retrieve information like group id, name etc. for a database. Below queries return filegroup ids for filegroups names Primary and DemoFileGroup in the AdventureWorksDW2017 database.

我创建了一个名为DemoFileGroup的文件组,以演示此功能的工作原理。 您可以检查系统视图sys.sysfilegroups以检索数据库的信息,例如组ID,名称等。 下面的查询返回AdventureWorksDW2017数据库中文件组名称Primary和DemoFileGroup的文件组ID。

返回对象名称的元数据函数 (Metadata Functions returning Object Names)

T-SQL OBJECT_NAME()元数据函数 (T-SQL OBJECT_NAME() metadata function)

OBJECT_NAME() function returns the name of the database object based on the given Object ID.

OBJECT_NAME()函数根据给定的对象ID返回数据库对象的名称。

函数OBJECT_NAME()的语法 (Syntax of function OBJECT_NAME())

Below is the syntax of the function. Basically, we need to pass ObjectID in this function to get the Object name.

下面是该函数的语法。 基本上,我们需要在此函数中传递ObjectID以获得对象名称。

OBJECT_NAME ( object_id [, database_id ] )

OBJECT_NAME(object_id [,database_id])

Where:

哪里:

  • object_id is int and the ID of the objectobject_id是int,对象的ID
  • database_id is int as well and belongs to the ID of the database where the object is expected to existdatabase_id也为int,并且属于预期对象存在的数据库的ID。

函数OBJECT_NAME()的示例 (Examples of function OBJECT_NAME())

  1. The following example makes use of the function OBJECT_NAME() to retrieve object name along with all other columns in the DMV sys.dm_db_index_physical_stats. for all objects in the database

    下面的示例利用函数OBJECT_NAME()来检索对象名称以及DMV sys.dm_db_index_physical_stats中的所有其他列。 对于数据库中的所有对象

    SELECT
    OBJECT_NAME(object_id) AS 'Object Name',*
    FROM sys.dm_db_index_physical_stats (NULL,NULL,NULL,NULL,NULL)
    ORDER BY index_type_desc
    
  2. This function can also be used with system catalog views like sys.objects, sys.tables etc. and WHERE clause to return columns specified by this function in the WHERE clause as shown below. To keep things simpler for you, I will continue with the same table, DimEmployee and make sure current database context points to the database, AdventureWorksDW2017

    此函数还可以与sys.objects,sys.tables等系统目录视图和WHERE子句一起使用,以返回此函数在WHERE子句中指定的列,如下所示。 为了简化您的工作,我将继续使用同一表DimEmployee并确保当前数据库上下文指向数据库AdventureWorksDW2017

    DECLARE @ObId int;
    SET @ObId = (SELECT OBJECT_ID('dbo.DimEmployee', 'U'));
    SELECT name AS Name, object_id AS ObjectID, type_desc AS 'Desc' FROM sys.tables
    WHERE name = OBJECT_NAME(@ObId)
    

T-SQL DB_NAME()元数据函数 (T-SQL DB_NAME() metadata function)

This function returns the name of the database.

此函数返回数据库的名称。

函数DB_NAME的语法() (Syntax of function DB_NAME ())

DB_NAME ( [ database_id ] )

DB_NAME([database_id])

Where database_id is the id of the database to be retrieved. This function works without this id as well, in that case, the current database name is returned.

其中database_id是要检索的数据库的ID。 此函数也可以在没有此ID的情况下工作,在这种情况下,将返回当前数据库名称。

函数DB_NAME()的示例 (Examples of function DB_NAME())

In the below examples, DB_NAME() returns the name of the database in use and by passing database id as 6. This function also helps in verification, here it verifies if the current database value is AdventureWorksDW2017 or not, and accordingly it takes further action.

在下面的示例中,DB_NAME()返回正在使用的数据库的名称,并通过将数据库ID传递为6。此函数还有助于验证,此处它验证当前数据库值是否为AdventureWorksDW2017,并因此采取进一步的措施。

SELECT DB_NAME()
SELECT DB_NAME(6)
IF DB_NAME() = 'AdventureWorksDW2017'
SELECT 'You are using database ' + DB_NAME()
ELSE
SELECT 'You are using the wrong DB'
  • note – These examples might look simple and straight-forward because here we are just referring to a single object in a single database, however, in reality, SQL professionals often have to deal with a large number of tables in several databases at the same time, in such scenarios, these functions come in handy -这些例子可能看起来简单和直接的,因为我们在这里只是指一个对象在一个单一的数据库,但是,在现实中,SQL专业人员经常需要处理多个数据库在大量的表同时,在这种情况下,这些功能会派上用场

T-SQL COL_NAME()元数据函数 (T-SQL COL_NAME() metadata function)

This function returns the name of a column for a corresponding table id and column id.

此函数返回对应表ID和列ID的列名。

函数COL_NAME的语法() (Syntax of function COL_NAME ())

COL_NAME ( table_id , column_id )

COL_NAME(table_id,column_id)

函数COL_NAME()的示例 (Examples of function COL_NAME())

The below example returns the name of the 6th and 10th column in a table, dbo.DimEmployee.

下面的示例返回表dbo.DimEmployee中第6列和第10列的名称。

SELECT * FROM DimEmployee
SELECT COL_NAME(OBJECT_ID('dbo.DimEmployee'), 6) AS ColFirstName,
COL_NAME(OBJECT_ID('dbo.DimEmployee'), 10) AS ColTitle

T-SQL FILE_NAME()元数据功能 (T-SQL FILE_NAME() metadata function)

This function returns the name of the file for the given file ID.

此函数返回给定文件ID的文件名。

函数FILE_NAME()的语法 (Syntax of function FILE_NAME())

FILE_NAME (file_id)

FILE_NAME(file_id)

函数FILE_NAME()的示例 (Examples of function FILE_NAME())

The below example returns the file names for ID =1 and ID=2 in the AdventureWorksDW2017 database.

下面的示例在AdventureWorksDW2017数据库中返回ID = 1和ID = 2的文件名。

SELECT * FROM sys.database_files
SELECT FILE_NAME(1) AS 'FileName1', FILE_NAME(2) AS 'FileName2'

T-SQL FILEGROUP_NAME()元数据函数 (T-SQL FILEGROUP_NAME() metadata function)

This returns the filegroup name for the given filegroup ID.

这将返回给定文件组ID的文件组名称。

函数FILEGROUP_NAME()的语法 (Syntax of function FILEGROUP_NAME())

FILEGROUP_NAME ( filegroup_id )

FILEGROUP_NAME(filegroup_id)

函数FILEGROUP_NAME()的示例 (Examples of function FILEGROUP_NAME())

The following examples return filegroup name for the specified filegroup ids in the AdventureWorksDW2017 database.

以下示例返回AdventureWorksDW2017数据库中指定文件组ID的文件组名称。

SELECT * FROM sys.filegroups
SELECT FILEGROUP_NAME(1) AS 'File Group Name'
SELECT FILEGROUP_NAME(2) AS 'File Group Name'

返回对象属性的函数 (Functions returning Object Properties)

T-SQL OBJECTPROPERTY()元数据函数 (T-SQL OBJECTPROPERTY() metadata function)

OBJECTPROPERTY() metadata function returns information related to several properties about objects in the current database.

OBJECTPROPERTY()元数据函数返回与当前数据库中对象的几个属性有关的信息。

函数OBJECTPROPERTY()的语法 (Syntax of function OBJECTPROPERTY())

OBJECTPROPERTY ( id , property )

OBJECTPROPERTY(id,property)

Where:

哪里:

  • id is the object id and is intid是对象ID,并且是int
  • here to understand these properties此处的属性名称部分以了解这些属性

函数OBJECTPROPERTY()的示例 (Examples of function OBJECTPROPERTY())

  1. The following examples check if the table DimEmployee, has a foreign key reference and is memory- optimized. The value 1 means true and 0 means false

    以下示例检查表DimEmployee是否具有外键引用并且是否经过内存优化。 值1表示true,0表示false

    SELECT OBJECTPROPERTY(OBJECT_ID(N'AdventureWorksDW2017.dbo.DimEmployee'), 'TableHasForeignRef');
    SELECT OBJECTPROPERTY(OBJECT_ID(N'AdventureWorksDW2017.dbo.DimEmployee'), 'TableIsMemoryOptimized');
    
  2. Here we are using this function to validate a property, IsUniqueCnst on the table DimEmployee and based on the results, printing the statements

    在这里,我们使用此函数来验证表DimEmployee上的属性IsUniqueCnst并基于结果打印语句

    USE AdventureWorksDW2017
    IF OBJECTPROPERTY(OBJECT_ID('dbo.DimEmployee'), 'IsUniqueCnst') = 0PRINT 'This table does not have a unique constraint'
    ELSEPRINT 'This table has a unique constraint';
    

T-SQL OBJECTPROPERTYEX()元数据函数 (T-SQL OBJECTPROPERTYEX() metadata function)

This function works on similar lines as function OBJECTPROPERTY(), returning information about the properties of objects in the database. Microsoft added some extra properties in this function and prefixed this function by ex.

该函数与OBJECTPROPERTY()函数在相似的行上工作,返回有关数据库中对象属性的信息。 Microsoft在此函数中添加了一些额外的属性,并在此函数前加上了ex。

函数OBJECT_PROPERTYEX()的语法 (Syntax of function OBJECT_PROPERTYEX())

OBJECTPROPERTYEX ( id , property )

OBJECTPROPERTYEX(id,property)

The Id here represents the id of an object that is being looked up in the database and property returns the property name. The only difference is that this function returns sql_variant and can support non-integer properties.

此处的ID代表正在数据库中查找的对象的ID,属性返回属性名称。 唯一的区别是此函数返回sql_variant并可以支持非整数属性。

函数OBJECT_PROPERTYEX()的示例 (Examples of function OBJECT_PROPERTYEX())

The following example returns the base type of our table DimEmployee which is a User Table (U).

以下示例返回表DimEmployee的基本类型,该类型是用户表(U)。

SELECT OBJECTPROPERTYEX ( object_id('dbo.DimEmployee'), N'BaseType');

T-SQL DATABASEPROPERTYEX()元数据函数 (T-SQL DATABASEPROPERTYEX() metadata function)

This function returns information related to several properties of the specified database.

此函数返回与指定数据库的多个属性有关的信息。

函数DATABASEPROPERTYEX()的语法 (Syntax of function DATABASEPROPERTYEX())

DATABASEPROPERTYEX ( database , property )

DATABASEPROPERTYEX(数据库,属性)

Where, database represents the name of the database for which this function will return the property information and property denotes the property that needs to be returned.

其中,database表示此函数将为其返回属性信息的数据库的名称,而property表示需要返回的属性。

There are a lot of database properties that this metadata function supports, you can go to the property name section over here to understand all these properties.

此元数据功能支持许多数据库属性,您可以转到此处的属性名称部分以了解所有这些属性。

函数DATABASEPROPERTYEX()的示例 (Examples of function DATABASEPROPERTYEX())

In the following examples, we can retrieve information like database collation and status using the below properties.

在以下示例中,我们可以使用以下属性检索信息,例如数据库排序规则和状态。

SELECT DATABASEPROPERTYEX('AdventureWorksDW2017', 'Collation') AS CollationPpty
SELECT DATABASEPROPERTYEX('AdventureWorksDW2017', 'Status') AS StatusPpty

T-SQL COLUMNPROPERTY()元数据函数 (T-SQL COLUMNPROPERTY() metadata function)

This function returns information about a column.

此函数返回有关列的信息。

函数COLUMNPROPERTY()的语法 (Syntax of function COLUMNPROPERTY ())

COLUMNPROPERTY ( id , column , property )

COLUMNPROPERTY(id,column,property)

Where, ID means the id of the table or procedure, the column represents the name of the column and property here refers to the type of information that this function will return. Like objectproperty() and databaseproperty() functions, there are too many properties to cover here, please refer here to learn about these properties.

其中,ID表示表或过程的ID,列表示列的名称,此处的属性表示此函数将返回的信息的类型。 与objectproperty()和databaseproperty()函数一样,这里有太多的属性无法覆盖,请参考此处以了解这些属性。

函数示例COLUMNPROPERTY() (Examples of function COLUMNPROPERTY ())

The following examples return properties to check if the column allows null values, is computed and is an identity column for three different columns in the DimEmployee table of AdventureWorksDW2017 database.

以下示例返回属性,以检查该列是否允许空值,是否已计算并且是AdventureWorksDW2017数据库的DimEmployee表中三个不同列的标识列。

SELECT COLUMNPROPERTY( OBJECT_ID('DimEmployee'),'MiddleName','AllowsNull') AS 'IsColNull'
SELECT COLUMNPROPERTY( OBJECT_ID('DimEmployee'),'EmployeeKey','IsComputed') AS 'IsComputed'
SELECT COLUMNPROPERTY( OBJECT_ID('DimEmployee'),'EmployeeKey','IsIdentity') AS 'IsIdentity'

其他一些T-SQL元数据功能 (Some more T-SQL metadata functions )

Let’s look at some of the other metadata functions that provide equally important information about the database and its objects.

让我们看一下其他一些元数据功能,它们提供有关数据库及其对象的同等重要的信息。

T-SQL @@ PROCID元数据功能 (T-SQL @@PROCID metadata function)

As we can make out from the name, @@procid, this function returns the ID of the current procedure, by procedure here, I mean, stored procedure, user-defined function (UDF), or a trigger.

从名称@@ procid可以看出,该函数返回当前过程的ID,这里的过程是存储过程,用户定义函数(UDF)或触发器。

函数@@ PROCID的语法 (Syntax of function @@PROCID)

@@PROCID

@@ PROCID

This function returns int type.

此函数返回int类型。

函数@@ PROCID的示例 (Examples of function @@PROCID)

The following code makes use of the @@PROCID function in the stored procedure and executing this procedure returns the current if of this stored procedure, DemoProcID.

以下代码在存储过程中使用@@ PROCID函数,执行此过程将返回此存储过程的当前DemoProcID。

CREATE PROC DemoProcID
AS BEGIN
SELECT @@PROCID AS ProcID
END
Exec DemoProcID

T-SQL OBJECT_DEFINITION()元数据函数 (T-SQL OBJECT_DEFINITION() metadata function)

This function helps to return the T-SQL code of the object specified, it can be a constraint, stored procedure, function, view etc.

该函数有助于返回指定对象的T-SQL代码,它可以是约束,存储过程,函数,视图等。

函数OBJECT_ DEFINITION()的语法 (Syntax of function OBJECT_ DEFINITION ())

OBJECT_DEFINITION ( object_id )

OBJECT_DEFINITION(object_id)

Syntax of this function makes use of object_id which is int, the similar way we have seen above for other OBJECT related functions. This functions returns type nvarchar(max).

该函数的语法使用的是int的object_id,类似于我们上面在其他与OBJECT相关的函数中看到的方式。 此函数返回nvarchar(max)类型。

函数OBJECT_ DEFINITION()的示例 (Examples of function OBJECT_ DEFINITION ())

The following example returns the definition of a view, vDMPrep in database AdventureWorksDW2017. Copy and paste the result value in a new query window to see the CREATE definition of this view.

以下示例返回数据库AdventureWorksDW2017中视图的定义vDMPrep。 将结果值复制并粘贴到新的查询窗口中,以查看此视图​​的CREATE定义。

SELECT OBJECT_DEFINITION (OBJECT_ID(N'dbo.vDMPrep'))

T-SQL COL_LENGTH()元数据函数 (T-SQL COL_LENGTH() metadata function)

This function provides the length of the column, in bytes.

此函数提供列的长度(以字节为单位)。

函数COL_LENGTH()的语法 (Syntax of function COL_LENGTH())

COL_LENGTH ( ‘table’ , ‘column’ )

COL_LENGTH('table','column')

Where table represents table name and column is the name of the column whose length is returned by this function.

其中table代表表名,column是该函数返回其长度的列名。

函数COL_LENGTH()的示例 (Examples of function COL_LENGTH())

We can retrieve lengths of columns FirstName and Gender in table dimEmployee using the below examples.

我们可以使用以下示例在表dimEmployee中检索FirstName和Gender列的长度。

SELECT COL_LENGTH('dbo.dimEmployee','FirstName');
SELECT COL_LENGTH('dbo.dimEmployee','Gender');

T-SQL PARSENAME()元数据函数 (T-SQL PARSENAME() metadata function)

This function returns the specified part of the given object name. These parts can be database name, schema/owner name and database name etc.

此函数返回给定对象名称的指定部分。 这些部分可以是数据库名称,架构/所有者名称和数据库名称等。

函数PARSENAME()的语法 (Syntax of function PARSENAME())

PARSENAME ( ‘object_name’ , object_part )

PARSENAME('object_name',object_part)

Where object_name is the name of the object for which to return the specified object part and object_part is the part of the object to be returned. The return type of object_part is int and these values can be as follows:

其中object_name是要为其返回指定对象部分的对象的名称,而object_part是要返回的对象部分。 object_part的返回类型为int,这些值可以如下:

1 – Object Name, 2 – Schema Name, 3 – Database Name, 4 – Server Name

1 –对象名称,2 –架构名称,3 –数据库名称,4 –服务器名称

函数PARSENAME()的示例 (Examples of function PARSENAME())

The examples shown below, return information like schema name and database name for DimEmployee table that we had used throughout this article in the AdventureWorksDW2017 database.

下面显示的示例返回在整篇文章中我们在AdventureWorksDW2017数据库中使用的DimEmployee表的信息,例如架构名称和数据库名称。

SELECT PARSENAME('dbo.DimEmployee', 1) AS ObjectName ,
PARSENAME('dbo.DimEmployee', 2) AS SchemaName,
PARSENAME('AdventureWorksDW2017.dbo.DimEmployee', 3) AS DatabaseName

观察结果 (Observations)

We can conclude the following observations from our exercise above on the metadata functions:

通过上面关于元数据功能的练习,我们可以得出以下结论:

  • Metadata functions are both scalar and non-deterministic, implying that these functions return only single value, and also the result values vary even if we pass the same input parameters in them 元数据函数既是标量函数也不是确定性函数,这意味着这些函数仅返回单个值,并且即使我们在其中传递相同的输入参数,结果值也会发生变化
  • These functions are easily queried with a simple SELECT statement 使用简单的SELECT语句即可轻松查询这些功能
  • These functions return NULL on error 这些错误返回NULL
    • Majority of them use a suffix, ‘()’, for eg. Object_Id(), Columnproperty() etc. 其中大多数使用后缀'()',例如。 Object_Id(),Columnproperty()等。
    • A few are used with a prefix, ‘@@’, for eg. @@PROCID 少数几个带有前缀“ @@”,例如。 @@ PROCID
    • Some do not make use of any prefix or suffix, for eg. – NEXT VALUE FOR 有些不使用任何前缀或后缀,例如。 –的下一个价值

结论 (Conclusion )

SQL Server supports metadata functions in abundance, and in this article, I have put my best foot forward to cover all the important and most-used T-SQL metadata functions in SQL Server. I might have skipped a few, but I am sure with the examples demonstrated above, you will be able to understand and apply them with ease in your SQL Server projects. Happy coding

SQL Server中的T-SQL元数据功能的完整指南相关推荐

  1. SQL Server中的动态SQL

    In this article, we will review how to construct and execute dynamic SQL statements in SQL Server wi ...

  2. sql server 数组_如何在SQL Server中实现类似数组的功能

    sql server 数组 介绍 (Introduction) I was training some Oracle DBAs in T-SQL and they asked me how to cr ...

  3. SQL Server中常用的SQL语句

    1.概述 2.查询概述 3.单表查询 4.连接查询 5.带有exists的相关子查询 6.SQL的集合操作 7.插入操作 8.删除操作 9.修改操作 10.数据定义 11.视图 1.概述 名词 笛卡尔 ...

  4. SQL Server中的空间SQL数据类型

    空间数据类型 (Spatial data type) SQL server furnishes us with the geometry and geography SQL data types fo ...

  5. Sql server中 如何用sql语句创建视图 及 视图的作用

    1.视图的作用 视图的作用: 第一点:使用视图,可以定制用户数据,聚焦特定的数据. 解释: 在实际过程中,公司有不同角色的工作人员,我们以销售公司为例的话, 采购人员,可以需要一些与其有关的数据,而与 ...

  6. 在sql server中如何用sql语句查看表结构信息?

    执行如下sql: sp_help  tablename; 再如: SELECT  * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'APN_U ...

  7. sql数据库备份默认路径_在Linux上SQL Server中更改默认数据库文件和备份路径

    sql数据库备份默认路径 In a previous article, we explored the process to change default SQL dump file location ...

  8. MySQL、SQL Server中字符串拼接

    一.MySQL中字符串拼接 1.使用加号"+"实现 在Java.C#等编程语言中字符串的拼接可以通过加号"+"来实现, 在MySQL中也可以使用加号" ...

  9. mysql2008 limit,在SQL Server中实现 Limit m, n 的功能

    在SQL Server中实现 Limit m, n 的功能 (2012-03-14 18:17:43) 标签: 杂谈 在MySQL中,可以用 Limit 来查询第 m 列到第 n列的记录,例如: se ...

最新文章

  1. 作为CTO,我为什么必须要求代码进行Code Review!
  2. 内存泄漏和内存溢出的关系和区别
  3. python可以干什么工作-python到底能做什么
  4. 无法读取内存属于错误吗_深入了解 JavaScript 内存泄露
  5. SQL搜索转为XML搜索
  6. No module named ‘skimage.metrics‘在Anaconda3中的解决方法
  7. matlab保存格式可以用cad打开文件,怎么将TXT文件导入CAD中生成图形
  8. async await 的前世今生
  9. Mac 开机没声音了?只需 2 招关闭/恢复Mac开机音效「咚」
  10. Java内存模型与Jvm内存模型
  11. Quartz配置文件quartz.properties加载
  12. html期末作业代码网页设计 我的家乡网站设计——我的家乡-四川成都(4页) HTML+CSS+JavaScript
  13. 南方cass快捷键命令修改在哪_南方CASS快捷命令
  14. 扩展欧几里得算法详解
  15. python求零点极点增益_传递函数的零点、极点怎么解释,有什么用?
  16. 智慧树期末考试可以切换页面吗_智慧树考试可以切换界面吗?中途可以退出吗...
  17. uniapp API 第三方服务
  18. 图像卡通化生成(Image Cartoonization):最新最全19篇汇总
  19. openlayer+虚线、实线
  20. 2022-2028年全球与中国红外(IR)摄像机行业市场前瞻与投资战略规划分析

热门文章

  1. 30岁学编程python_我30岁了,转行学编程可以吗? 排除法告诉你答案
  2. [导入]C++ OpenGL底层和C# GUI无缝联合!
  3. 心得 | 《用得上的商学课》 004 边际成本 | 飞机起飞前的座位,只卖一块钱?...
  4. Java-Android【2】-弹出对话框
  5. nopcommerce 二次开发
  6. 和菜鸟一起学产品之产品经理的三大文档
  7. JavaScript格式化金额及格式化输出
  8. 利用JDK1.5的工具对远程的Java应用程序进行监测(摘录)
  9. 31个用来测试你网站各项性能的免费在线工具
  10. 转 .net里如何判断中文字符长度