SQL Server 2000General discussion of Microsoft SQL Server -- for topics that don't fit in one of the more specific SQL Server forums. version 2000 only. There's a new forum for SQL Server 2005.
Welcome to the p2p.wrox.com Forums.
You are currently viewing the SQL Server 2000 section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
I'm trying to write a User Defined Function on SQL Server, and the function need to connect to another database to get some values. Is this possible? Can a function in one database communicate to another database on the same server?
Or, is there a possiblity of calling a user defined function on one database from another database? If so could you please provide an example.
Yes, getting data from another database on the same server is very simple. When you reference the table, add the db name to the beginning of the reference.
That helps. I'm still not able to make my function work. I was trying to write a function to get a value from a table and return that value. Here's what I did:
CREATE FUNCTION dbo.getProgramCode
( @id numeric )
RETURNS table
AS
RETURN SELECT [INquiry].[dbo].[tblAcadProg].[acad_prog]
from [INquiry].[dbo].[tblAcadProg]
Where [INquiry].[dbo].[tblAcadProg].[acad_prog_id]= @id
I don't want a table datatype returned. A varchar would do coz there will always be just one value. I could not figure out how I can do it. And when I try to reference this function I get "Invalid object name" error.
CREATE FUNCTION dbo.getProgramCode
( @id numeric )
RETURNS table
AS
RETURN SELECT acad_prog
from [INquiry].[dbo].[tblAcadProg]
Where acad_prog_id]= @id
Could not make the function work with returning a varchar. Tried replacing table with varchar but I get error.
CREATE FUNCTION dbo.getProgramCode
( @id numeric )
RETURNS varchar
AS
RETURN SELECT [INquiry].[dbo].[tblAcadProg].[acad_prog]
from [INquiry].[dbo].[tblAcadProg]
Where [INquiry].[dbo].[tblAcadProg].[acad_prog_id]= @id
Is this code snippet correct? The column I'm selecting is varchar as well.
CREATE FUNCTION dbo.getProgramCode
( @id numeric )
RETURNS varchar(1000)
AS
BEGIN
DECLARE @TEMP VARCHAR(1000)
SELECT @TEMP = [INquiry].[dbo].[tblAcadProg].[acad_prog]
from [INquiry].[dbo].[tblAcadProg]
Where [INquiry].[dbo].[tblAcadProg].[acad_prog_id]= @id
RETURN(@TEMP)
END
quote:Originally posted by om_prakash
Please try this:
CREATE FUNCTION dbo.getProgramCode
( @id numeric )
RETURNS varchar(1000)
AS
BEGIN
DECLARE @TEMP VARCHAR(1000)
SELECT @TEMP = [INquiry].[dbo].[tblAcadProg].[acad_prog]
from [INquiry].[dbo].[tblAcadProg]
Where [INquiry].[dbo].[tblAcadProg].[acad_prog_id]= @id
RETURN(@TEMP)
END