If exists table dynamic sql from variable database id

  • Hi 

    I want to write if the table exists in the database in dynamic sql then select from that table .

    I have written this but i want to use in if then

    DECLARE @SQL NVARCHAR(MAX);
    set @SQl = 'SELECT * FROM ['+ @DBID+'].sys.objects where NAME LIKE ''%DDSC_MappedDimension%'' '

    SET @RunTimeQuery = 'SELECT distinct MAPPEDDIMENSIONCODE,DIMENSION_TYPE FROM ['+ @DBID+'].dbo.DDSC_MappedDimension WHERE MAPPEDDIMENSIONCODE = ''' + @code + '''' + 'and DIMENSION_TYPE = ''' + @Dimension_Type +''''

  • mnr123 - Sunday, July 16, 2017 1:17 PM

    Hi 

    I want to write if the table exists in the database in dynamic sql then select from that table .

    I have written this but i want to use in if then

    DECLARE @SQL NVARCHAR(MAX);
    set @SQl = 'SELECT * FROM ['+ @DBID+'].sys.objects where NAME LIKE ''%DDSC_MappedDimension%'' '

    SET @RunTimeQuery = 'SELECT distinct MAPPEDDIMENSIONCODE,DIMENSION_TYPE FROM ['+ @DBID+'].dbo.DDSC_MappedDimension WHERE MAPPEDDIMENSIONCODE = ''' + @code + '''' + 'and DIMENSION_TYPE = ''' + @Dimension_Type +''''

    Your logic sounds pretty straightforward.

    DECLARE @Name varchar(128) = 'dbo.Test';
    DECLARE @SQL Varchar(200);

    IF OBJECT_ID(@Name, 'U') IS NOT NULL
    BEGIN
        --TODO: define your query here
        EXECUTE (@SQL);
    END;

Viewing 2 posts - 1 through 1 (of 1 total)

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