我想打印一个包含200个引用表名称(refTableA,refTableB等)的列表以及每个表的选项集(refTableAID,Description,Code,SortOrder)。一些选项集是单个记录;其他人可能包括30多条记录。 下面的脚本将Description,Code和SortOrder数据插入到临时表中。我对如何将表名(refTableA)插入RefTableName字段以及将ID(RefTableAID)插入RefTableNameId字段感到困惑。非常感谢任何帮助。
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL DROP TABLE #Temp
DECLARE @table nvarchar(150)
DECLARE @sqlinsert nvarchar(max)
DECLARE C1 CURSOR FOR SELECT TABLE_NAME FROM Information_schema.tables where TABLE_NAME like 'ref%'
Create table #Temp
(
RefTableName nvarchar(150),
RefTableNameId int,
Description nvarchar(100),
Code nvarchar(50),
SortOrder Decimal(5,2)
)
OPEN C1
FETCH next FROM C1 INTO @table
WHILE @@FETCH_STATUS =0
BEGIN
set @sqlinsert='Insert into #Temp (Description, Code, SortOrder)
Select Description,Code,SortOrder from *tbl*'
set @sqlinsert = REPLACE(@sqlinsert,'*tbl*',@table)
Print (@sqlinsert)
Exec (@sqlinsert)
FETCH next FROM C1 INTO @table
END
CLOSE C1
DEALLOCATE C1
SELECT * from #Temp
答案 0 :(得分:0)
这可能是你可以使用的东西
SELECT *
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
WHERE (PK.TABLE_SCHEMA= '<SCHEMA>' AND PK.TABLE_NAME = '<PK_Table>')
AND (FK.TABLE_SCHEMA= '<SCHEMA>' AND FK.TABLE_NAME = '<FK_TABLE>');