SQL Server中的T-SQL元数据功能的完整指南

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中的可编程性 。 双击“ 功能系统功能”,然后展开“ 元数据 功能”以查看其下的元数据功能的完整列表。

Selecting T-SQL Metadata Functions in SSMS.

And below is the extended list of metadata functions:

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

Complete list of T-SQL metadata functions in SSMS.

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中引用这些功能的唯一参考。

List of T- SQL metadata functions in 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'
    

    Object_Id() metadata function in SQL Server.

  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'
    

    Object_Id() metadata function in SQL Server.

    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
    

    Objectid value is stored in sys.objects view in SSMS.

  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'
    

    Example of metadata function OBJECT_ID() in SQL Server.

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'
    

    Example of metadata function DB_ID() in SQL Server.

  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();

    Example of metadata function DB_ID() in SQL Server.

    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

Examples of metadata function FILE_IDEX() in SQL Server.

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');

Examples of metadata function FILEGROUP_ID() in SQL Server.

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。

Examples of metadata function FILEGROUP_ID() in SQL Server.

返回对象名称的元数据函数 (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 object

    object_id是int,对象的ID
  • database_id is int as well and belongs to the ID of the database where the object is expected to exist

    database_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
    

    Metadata function OBJECT_NAME() example in SQL Server

  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)
    

    Metadata function OBJECT_NAME() in SQL Server.

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'

Example of metadata function DB_NAME() in SQL Server.
  • 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

Example of metadata function COL_NAME() in SQL Server.

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'

Example of metadata function FILE_NAME() in SQL Server.

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'

Examples of metadata function FILEGROUP_NAME() in SQL Server.

返回对象属性的函数 (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 int

    id是对象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');
    

    OBJECTPROPERTY() metadata function in SQL Server.

  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') = 0
      PRINT 'This table does not have a unique constraint'
    ELSE
      PRINT 'This table has a unique constraint';
    

    Metadata function OBJECTPROPERTY() example in SQL Server.

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');

Metadata function OBJECTPROPERTYEX() example in SQL Server.

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

Examples of metadata function DATABASEPROPERTYEX() in SQL Server

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'

Examples of metadata function COLUMNPROPERTY() in SQL Server.

其他一些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

Example of metadata function @@PROCID in SQL Server.

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'))

Metadata function OBJECT_DEFINITION() example in SQL Server.

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');

Examples of metadata function COL_LENGTH() in SQL Server

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

Examples of metadata function PARSENAME() in SQL Server

观察结果 (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大量支持元数据功能,在本文中,我竭尽全力介绍了SQL Server中所有重要且最常用的T-SQL元数据功能。 我可能略过了一些,但是我可以肯定上面展示的示例,您将能够轻松地在SQL Server项目中理解和应用它们。 快乐编码🙂

翻译自: https://www.sqlshack.com/a-complete-guide-to-t-sql-metadata-functions-in-sql-server/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值