How to write a Function that can return a value from a dynamic database?

I need to get a value from a dynamic data base, and I thought that the best way to do this was by using a scalar function.

I'm not too experianced in writting Functions... so I thought I'd post here and see if it is possible, and if so, how

Basically, I will be using 3 parameter:

  • varchar @DataSource (the datasource string in the form of "server=SRV;uid=USER;pwd=PWD;database=DB;")
  • int @RecordId (the primary key id column of the table)
  • varchar @TableName (the name of the table)

All tables have this common structure:

  • INT [id]
  • VARCHAR [title]

I want to return the Varchar @Title based on my provided parameters.

How would I go about doing this




Answer this question

How to write a Function that can return a value from a dynamic database?

  • HDVD

    You cannot do this using a TSQL UDF in SQL Server 2000/2005. Basically, the functionality you are requesting for requires dynamic SQL and you cannot use dynamic SQL within TSQL UDFs. You can do this from a TSQL stored procedure. You can however write a CLR UDF in SQL Server 2005. But I am not sure what you are trying to do though. Why can't you create a linked server for the data source and write distributed queries using 4-part names This approach is much more easier to integrate and use in other queries.

  • Tikkam J

    I think this might be a question for Reporting Services forum on how to do this from the report itself. You can find out about linked servers in Books Online. You can start with link below:


  • Chris Keeble

    I see...

    I'm not really sure what a linked server is, and whether it would be the best solution.

    What I am basically trying to achieve is:

    Reporting service pull records from db_a, which have reference to db_x (in the form of datasource, record_id, table_name)... and I want to get the title of the reference into my report.

    I'm now writing this in code, so that a new bit of sql execution needs to take place, but I'm sure this is very inefficient.



  • How to write a Function that can return a value from a dynamic database?