SQL-Statement with dynamic table-names or redesign?

前端 未结 3 2130
慢半拍i
慢半拍i 2021-01-26 01:44

I have a MS SQL 2008 database which stores data for creating a weighted, undirected graph. The data is stored in tables with the following structure:

[id1] [int]         


        
3条回答
  •  忘了有多久
    2021-01-26 01:56

    Maybe I did not understand everything, but:

    CREATE PROCEDURE dbo.GetMyData (
         @TableName AS varchar(50)
        )
    AS 
    BEGIN
        IF @TableName = 'Table_1' 
            BEGIN
                SELECT  id1
                       ,id2
                       ,[weight]
                FROM    dbo.Table_1
            END
    
        IF @TableName = 'Table_2' 
            BEGIN
                SELECT  id1
                       ,id2
                       ,[weight]
                FROM    dbo.Table_2
            END
    END 
    

    and then:

    EXEC dbo.GetMyData @TableName = 'Table_1' 
    

    A different technique involves using synonyms dynamically, for example:

    DECLARE @TableName varchar(50)
    SET @TableName = 'Table_1' 
    
    -- drop synonym if it exists
    IF object_id('dbo.MyCurrentTable', 'SN') IS NOT NULL 
        DROP SYNONYM MyCurrentTable ;
    
    -- create synonym for the current table
    IF @TableName = 'Table_1' 
        CREATE SYNONYM dbo.MyCurrentTable FOR dbo.Table_1 ;
    
    IF @TableName = 'Table_2' 
        CREATE SYNONYM dbo.MyCurrentTable FOR dbo.Table_2 ;
    
    -- use synonym
    SELECT  id1, id2, [weight] 
    FROM dbo.MyCurrentTable
    

提交回复
热议问题