是否可以在所有数据库中查询INFORMATION_SCHEMA.COLUMNS?看来必须指定USE db
。
我尝试过,但是在使用PowerShell Invoke-Sqlcmd
时它什么也没返回。
IF DB_ID('db') IS NOT NULL
BEGIN
SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'BID_BY_CPT_SPECIAL'
ORDER BY TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,ORDINAL_POSITION
;
END
此查询在PowerShell脚本中使用。
$q = @"
DROP TABLE IF EXISTS #Temp;
SELECT DatabaseName=cast('' as varchar(100))
, TABLE_NAME
, COLUMN_NAME
, DATA_TYPE
, ORDINAL_POSITION
Into #Temp
FROM INFORMATION_SCHEMA.COLUMNS
Where 1=0
Declare @SQL varchar(max) = '
USE ? ;
Insert Into #Temp
SELECT DatabaseName=''?''
, TABLE_NAME
, COLUMN_NAME
, DATA_TYPE
, ORDINAL_POSITION
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE ''BID_BY_CPT_SPECIAL''
ORDER BY TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,ORDINAL_POSITION
'
EXEC sp_MSforeachdb @SQL
Select * From #Temp
"@
foreach ($db in $DatabaseInstances) {
$r = Invoke-Sqlcmd -Query $q -ServerInstance $db
===更新
此查询正在使用Invoke-Sqlcmd
。
$q = @"
DROP TABLE IF EXISTS #Temp;
SELECT DatabaseName=cast('' as varchar(100))
,TABLE_NAME
,COLUMN_NAME
,DATA_TYPE
,ORDINAL_POSITION
,CHARACTER_MAXIMUM_LENGTH
,NUMERIC_PRECISION
,NUMERIC_SCALE
,IS_NULLABLE
Into #Temp
FROM INFORMATION_SCHEMA.COLUMNS
Where 1=0
Declare @SQL varchar(max) = '
USE ? ;
Insert Into #Temp
SELECT DatabaseName=''?''
,TABLE_NAME
,COLUMN_NAME
,DATA_TYPE
,ORDINAL_POSITION
,CHARACTER_MAXIMUM_LENGTH
,NUMERIC_PRECISION
,NUMERIC_SCALE
,IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE ''$TableName''
ORDER BY TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,ORDINAL_POSITION
'
EXEC sp_MSforeachdb @SQL
Select * From #Temp
"@
答案 0 :(得分:1)
看看sp_MSforeachdb
这会将数据收集到一个Temp表中。就个人而言,我会将您的WHERE
移至最后的SELECT
示例
SELECT DatabaseName=cast('' as varchar(100))
, TABLE_NAME
, COLUMN_NAME
, DATA_TYPE
, ORDINAL_POSITION
Into #Temp
FROM INFORMATION_SCHEMA.COLUMNS
Where 1=0
Declare @SQL varchar(max) = '
USE ? ;
Insert Into #Temp
SELECT DatabaseName=''?''
, TABLE_NAME
, COLUMN_NAME
, DATA_TYPE
, ORDINAL_POSITION
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE ''BID_BY_CPT_SPECIAL''
ORDER BY TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,ORDINAL_POSITION
'
EXEC sp_MSforeachdb @SQL
Select * From #Temp