Help me.

  • Hi,

    Look at following, it works fine.

    declare @EmpName varchar(50)

    declare @DBName varchar(50)

    select @DBName='EmpDB'

    SELECT @EmpName=EmpDB..Employee.LName from EmpDB..Employee

    I need to replace hardcoded EmpDB with variable @DBName because at runtime

    it is decided from where to select data. I tried following but it just assigns string

    to @EmpName.

    SELECT @EmpName= @DBName+ '..Employee.LName from ' + @DBName+'..Employee'

    Can somebody help me with any solution or workaround

    Thanks in anticipation

  • You need dynamic sql to make it work. Build your query and assign to a variable - typically @sql but it doesn't matter, then execute using either Exec(@SQL) or sp_executesql (@SQL).

    Andy

    http://www.sqlservercentral.com/columnists/awarren/

  • Try

    declare @EmpName varchar(50)

    declare @DBName varchar(50)

    declare @sql nvarchar(1000)

    set @DBName='EmpDB'

    set @sql = 'SELECT @EmpName=LName from '+@DBName

    exec sp_executesql @sql,N'@EmpName varchar(50) output',@EmpName output

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

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

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