• I would put PRINT statements after

    SET @DyQuery=...

    and before

    EXEC xp_cmdshell @command

    to see what those two variables contain. I would then try them manually, which will show errors more clearly, and then adjust the source code to generate any changes you make.

    That said, they look fine to me.

    "Invalid object name 'TEST.dbo.users'."

    Does this give you some rows, or an error?

    SELECT TOP 10 * FROM TEST.dbo.users