Using Dynamic T-SQL execution

  • Hi All,

    I'm new to tsql and would like to know how I can achieve something like the following. Running the results of the following script dynamically?

    "select 'use '+name+char(13)+' go'+char(13) +'select * from sysfiles' char(13)+'go'+char(13) from sysdatabases

  • Try this

     declare @sql nvarchar(4000)
    
    set @sql = ''
    select @sql = @sql + 'use '+name+' select * from sysfiles ' from sysdatabases
    exec sp_executesql @sql

    Or this

    sp_MSforeachdb @command1 = "use ? select * from sysfiles"

    Far away is close at hand in the images of elsewhere.
    Anon.

  • Hi dharmesh1234,

    quote:


    Hi All,

    I'm new to tsql and would like to know how I can achieve something like the following. Running the results of the following script dynamically?

    "select 'use '+name+char(13)+' go'+char(13) +'select * from sysfiles' char(13)+'go'+char(13) from sysdatabases


    take a look in BOL at sp_executesql for dynamic SQL.

    Ahem, I'm not sure what you're trying to achieve. Why do you want do dynamically query a table that only exist in master?

    Cheers,

    Frank

    --
    Frank Kalis
    Microsoft SQL Server MVP
    Webmaster: http://www.insidesql.org/blogs
    My blog: http://www.insidesql.org/blogs/frankkalis/[/url]

  • Thanks all, you've solved my problem.

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

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