我希望根据我通过(例如)输入的列名称来检索包含表x的数据库。我的WHERE声明。
到目前为止,我运行两个单独的SELECT查询。首先,我搜索解决方案中的哪些表包含特殊列。 其次,我必须在子查询中手动搜索所有结果数据库。
我希望具有这种动态性,以便在输入列名称时同时返回数据库和表。现在,我在数据库列中获得“ NULL”。
我设法仅使用db_name来获取当前数据库,但这不是我打算做的事。
db_name(db_id(table1.name)) AS "Database" , table1.name AS 'Table', column1.name AS 'Column'
FROM sys.columns column1
JOIN sys.tables table1 ON column1.object_id = table1.object_id
WHERE column1.name LIKE 'columnname'
ORDER BY "Table", "Column"
(SELECT "db" FROM sys.databases WHERE CASE WHEN state_desc = 'ONLINE' THEN
OBJECT_ID(QUOTENAME("db") + '.[dbo].' + '[database1]', 'U')
END IS NOT NULL)
上面的代码没有错误。但是,我无法获取数据库名称,也无法理解如何解决此问题。
由于我是SQL的新手,因此我已经使用了几篇较早的文章作为构建此代码的参考。:-)
在此先感谢您的协助。 Br。
答案 0 :(得分:0)
这提供了比您要求的更多的信息,但这是我必须创建数据库的数据字典的代码。您只需要更改第一个变量的值即可使其工作。
--Change this value
DECLARE @ColumnName sysname = 'YourColumnName';
IF OBJECT_ID( 'tempdb..#DataDictionary') IS NOT NULL
DROP TABLE #DataDictionary;
CREATE TABLE #DataDictionary(
TABLE_CATALOG sysname,
TABLE_SCHEMA sysname,
TABLE_NAME sysname,
ORDINAL_POSITION int,
COLUMN_NAME sysname,
DATA_TYPE sysname,
IS_NULLABLE varchar(8)
);
DECLARE @SQL NVARCHAR(MAX);
DECLARE dbs CURSOR LOCAL FAST_FORWARD
FOR
SELECT REPLACE( 'USE <<database_name>>;
INSERT INTO #DataDictionary
SELECT DB_NAME() AS TABLE_CATALOG,
s.name AS TABLE_SCHEMA,
t.name AS TABLE_NAME,
COLUMNPROPERTY(c.object_id, c.name, ''ordinal'') AS ORDINAL_POSITION,
c.name AS COLUMN_NAME,
CASE WHEN ty.name IN (''char'', ''varchar'', ''varbinary'', ''binary'') THEN CONCAT( ty.name, ''('', ISNULL( CAST(NULLIF(c.max_length, -1) AS varchar(4)), ''MAX''), '')'')
WHEN ty.name IN (''nchar'', ''nvarchar'') THEN CONCAT( ty.name, ''('', ISNULL( CAST(NULLIF(c.max_length, -1)/2 AS varchar(4)), ''MAX''), '')'')
WHEN ty.name IN (''numeric'', ''decimal'') THEN CONCAT( ty.name, ''('', c.precision, '','', c.scale, '')'')
ELSE ty.name END AS DATA_TYPE,
IIF(c.is_nullable = 1, ''NULL'', ''NOT NULL'') AS IS_NULLABLE
FROM sys.schemas s
JOIN sys.tables t ON s.schema_id = t.schema_id
JOIN sys.columns c ON t.object_id = c.object_id
JOIN sys.types ty ON c.user_type_id = ty.user_type_id
WHERE t.object_id NOT IN( SELECT major_id FROM sys.extended_properties WHERE minor_id = 0 AND class = 1 AND name = N''microsoft_database_tools_support'')
AND c.name = @ColumnName;', '<<database_name>>', name)
FROM sys.databases
WHERE database_id > 4 --No system databases
AND HAS_DBACCESS( name) = 1
AND state_desc = 'ONLINE'
OPEN dbs;
FETCH NEXT FROM dbs INTO @SQL;
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_executesql @SQL, N'@ColumnName sysname', @ColumnName;
FETCH NEXT FROM dbs INTO @SQL;
END;
CLOSE dbs;
DEALLOCATE dbs;
SELECT *
FROM #DataDictionary
ORDER BY TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION;
要获取所有列,只需删除动态代码AND c.name = @ColumnName
中的列名比较