在SQL Server数据库的所有表中查找某种类型的所有列


84

如何NTEXT在SQL Server数据库的所有表中找到特定类型的所有列(例如)?

我正在寻找一个SQL查询。

Answers:


120

您可以使用以下查询返回字段

SELECT table_name [Table Name], column_name [Column Name]
FROM information_schema.columns where data_type = 'NTEXT'

3
这也将包括意见
丹尼尔(Daniel)

1
这也将在Azure SQL(2018年8月)上运行,并且我使用它将列转换为nvarchar(max),因为NText将被弃用。alter table [tablename] alter column [columnname] nvarchar(max)。您可以将LEN(..)nvarchar等用于ntext。
JP赫勒蒙斯

@Daniel,如果您不希望包含视图,请在information_schema.tables上进行内部联接,如下所示:INNER JOIN INFORMATION_SCHEMA.TABLES t ON c.TABLE_NAME = t.TABLE_NAME AND t.TABLE_TYPE = 'BASE TABLE'
Mike

14

您将需要INFORMATION_SCHEMA。尝试类似:

SELECT c.* from INFORMATION_SCHEMA.columns c
INNER JOIN INFORMATION_SCHEMA.tables t ON t.table_name = c.table_name
WHERE c.data_type = 'int' AND t.table_type = 'base table'

7

你也可以尝试

SELECT OBJECT_NAME(c.OBJECT_ID) TableName, c.name ColumnName
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
WHERE t.name = 'ntext'
ORDER BY c.OBJECT_ID;
GO

2

您可以使用系统视图INFORMATION_SCHEMA.COLUMNS。该data_type列包含您要查找的内容。


2

我确实使用以下语句查找了可能包含二进制数据/文件的所有表。

SELECT 
    table_name 
FROM 
    INFORMATION_SCHEMA.TABLES T 
WHERE 
    T.TABLE_CATALOG = 'MyDatabase' AND 
    EXISTS ( 
        SELECT * 
        FROM INFORMATION_SCHEMA.COLUMNS C 
        WHERE 
            C.TABLE_CATALOG = T.TABLE_CATALOG AND 
            C.TABLE_SCHEMA = T.TABLE_SCHEMA AND 
            C.TABLE_NAME = T.TABLE_NAME AND 
            ( C.DATA_TYPE  = 'binary' OR
             C.DATA_TYPE  = 'varbinary' OR 
            C.DATA_TYPE  = 'text' OR
            C.DATA_TYPE  = 'ntext' OR
            C.DATA_TYPE  = 'image' )
            )
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.