2013-06-18 61 views
3

我有一個主表ResId主鍵。獲取具有唯一外鍵的表之間的關係的表名稱

ResId是超過200個表的外鍵。在這些表中插入ResId具有獨特的價值。

例如渣油在表1是1,7,50和表2是3,4,21和表3是2,6,81,...

哪有我從主表中獲得具有特定ResId的表名。

例如當渣油= 3結果是表2並且當渣油= 6結果爲表3

回答

1
Declare @ResourceWorkflowID Int = 8019--For Example 
Declare @Temp Table 
(
    TblName Varchar(100), 
    RowNum Int Identity(1,1) 
) 
Insert Into @Temp 
    Select Distinct Object_Name(F.Parent_Object_Id) AS TableName 
    From Sys.Foreign_Keys AS F 
    Inner Join Sys.Foreign_Key_Columns As Fc On F.Object_Id = Fc.Constraint_Object_Id 
     Where Col_Name(Fc.Parent_Object_Id, Fc.Parent_Column_Id) = 'ResourceWorkflowID' 
Declare @Counter Int = 1, @State Int = 0 
While(@Counter <= (Select Max(RowNum) From @Temp) And @State = 0) 
Begin 
    Declare @Str nVarchar(400) = '', @Name nVarchar(50) = '' 
    Select @Name = TblName From @Temp Where RowNum = @Counter 
    Set @Str = 'If Exists (Select ResourceWorkflowID From '[email protected]+' Where ResourceWorkflowID = '+Cast(@ResourceWorkflowID As Nvarchar(10))+') 
     Set @Cnt = ' + Cast(@Counter As Nvarchar(2)) 
    Exec Sp_ExecuteSql @Str,N'@Cnt Int Output', @[email protected] Output 
    Set @Counter += 1 
End 
Select TblName As TableName From @Temp Where RowNum = @State 
Go 
0

邏輯可以是以下:

1)插入所有的表名稱從sys.tables #temptable

2)使用光標檢查每個,如果它包含必要的ResID

2A)如表格的下一

2B)沒有去。如果是插入表名@Result

3)從@result打印的名字嗎?

0

好了,可能是我錯過了什麼,但我認爲應該工作:

CREATE FUNCTION dbo.GetForeignTableNameByID 
( 
    @id INT 
) 
RETURNS NVARCHAR(MAX) 
AS 
BEGIN 
    DECLARE @table_id INT; 
    DECLARE @table_name NVARCHAR(MAX); 
    DECLARE @sql NVARCHAR(MAX); 
    DECLARE @counts INT; 

    DECLARE tables_cursor CURSOR FOR 
    SELECT 
     FK.referenced_object_id 
    FROM 
     sys.foreign_key_columns as FK   
    WHERE 
     FK.parent_object_id = OBJECT_ID('<Your Initial Table Name>'); 

    OPEN tables_cursor; 

    FETCH NEXT FROM tables_cursor 
    INTO @table_id; 

    WHILE @@FETCH_STATUS = 0 
    BEGIN 

     SET @table_name = 
     (
      SELECT QUOTENAME(DB_NAME(database_id)) 
       + N'.' 
       + QUOTENAME(OBJECT_SCHEMA_NAME(object_id, database_id)) 
       + N'.' 
       + QUOTENAME(OBJECT_NAME(object_id, database_id)) AS TableName 
      FROM sys.dm_db_index_operational_stats(null, null, null, null) 
      WHERE object_id = @table_id 
     ); 

     IF @table_name != '' 
     BEGIN 

      SET @sql = 'SELECT @cnt = COUNT(*) FROM ' + @table_name + ' WHERE ResId = ' + CAST(@id AS NVARCHAR(MAX)); 

      EXECUTE sp_executesql @sql, N'@cnt int OUTPUT', @[email protected] OUTPUT           

      IF @counts > 0 
       RETURN @table_name 
     END; 

     FETCH NEXT FROM tables_cursor 
     INTO @table_id; 
    END; 

    CLOSE tables_cursor; 
    DEALLOCATE tables_cursor; 
    RETURN ''; 
END 
GO 

你必須與你的實際的表名稱替換「您最初的表名」。