How to create dynmaic virtual table using meata data tables

  • Hi

    i want to build query at runtime.

    i have some metadata tables where i can store table names and attribute names. so now how can i do CRUD operations.

  • Create a SQL in a Variable and execute using sp_executesql procedure.

  • DECLARE @GblTableName NVARCHAR(300)

    SET @GblTableName = '[tempdb].[dbo].[Temp' + REPLACE(CAST(NEWID() AS NVARCHAR(50)), '-', '') + ']'

    EXEC ('IF OBJECT_ID(''' + @GblTableName + ''') IS NOT NULL

    DROP TABLE ' + @GblTableName + '')

    exec('CREATE TABLE ' + @GblTableName + '

    (

    UserID NVARCHAR(100) ,

    ProductID NVARCHAR(100) ,

    Price NVARCHAR(100) ,

    ProductQty NVARCHAR(100) ,

    TotalPrice NVARCHAR(100) ,

    ReportPrice NVARCHAR(100)

    )')

    SET @ExecuteSql = N'INSERT INTO ' + @GblTableName + ' SELECT UserID ,ProductID ,Price,ProductQty,TotalPrice,ReportPrice

    FROM ( SELECT USERID ,

    PRODUCTID ,

    PRICE ,

    PRODUCTQTY ,

    TOTALPRICE ,

    REPORTPRICE ,

    DATAORDER

    FROM ABC) T '

    EXEC (@ExecuteSql)

  • Above example is only for reference and not the perfect solution.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply