Home Forums SQL Server 2008 T-SQL (SS2K8) How to bring in more than one column from left table in a CURSOR/dynamic sql query RE: How to bring in more than one column from left table in a CURSOR/dynamic sql query

  • dwain.c (11/6/2013)


    Alan.B (11/6/2013)


    You could do something like this (I changed @name to @names):

    DECLARE @names varchar(max);

    WITH names(n) AS

    (

    SELECT Name

    FROM dbo.iNamesExcel$

    FOR XML PATH('')

    )

    SELECT @names=CHAR(39)+LEFT(n,LEN(n)-1)+CHAR(39)

    FROM names

    Then, in your DSQL change your and displayName =

    to

    and displayName IN ( @names )

    Hope that makes sense. Let me know if you need clarification.

    I don't think that @names is going to be recognized within the scope of the Dynamic SQL.

    I was in a hurry and should have tested this my code before posting it:blush:. This is what I was trying to do (I am using sys.databases for a simplified demo that can be tested locally):

    WITH dbs(d) AS (SELECT 'tempdb' UNION ALL SELECT 'msdb')

    SELECT * INTO #dbs FROM dbs;

    DECLARE @names varchar(max),

    @sql varchar(1000);

    WITH names(n) AS

    (

    SELECT ''''+d +''','

    FROM #dbs

    FOR XML PATH('')

    )

    SELECT @names=LEFT(n,LEN(n)-2)

    FROM names;

    SET @sql=

    'SELECT * FROM sys.databases

    WHERE name IN (' + @names + ''')';

    EXEC (@sql);

    That said, the solution you posted was much better:-P

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001