3

我有一个带有ResId主键的主表。

ResId是超过 200 个表的外键。在这些表中插入具有唯一值的ResId 。

例如,表1 中的ResId1,7,50 ,表 2 是3,4,21,表 3 是2,6,81,...

如何从主表中获取具有特定ResId的表名。

例如当ResId=3结果是table2并且当ResId =6结果是table3

4

3 回答 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 '+@Name+' Where ResourceWorkflowID = '+Cast(@ResourceWorkflowID As Nvarchar(10))+')
        Set @Cnt = ' + Cast(@Counter As Nvarchar(2))
    Exec Sp_ExecuteSql @Str,N'@Cnt Int Output', @Cnt=@State Output
    Set @Counter += 1
End
Select TblName As TableName From @Temp Where RowNum = @State
Go
于 2013-06-19T03:58:42.993 回答
0

逻辑可能如下:

1)将所有表的名称从 sys.tables 插入到#temptable

2)使用游标检查每个是否包含必要的 ResID

2a)如果没有转到下一张桌子

2b)如果是,则将表名插入@result

3) 从@result 打印名称?

于 2013-06-18T08:22:41.220 回答
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', @cnt=@counts 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

您必须将“您的初始表名”替换为您的实际表名。

于 2013-06-18T08:47:05.383 回答