Solved

function to return table name

Posted on 2008-10-01
3
815 Views
Last Modified: 2012-08-14
From a stored procedure, can I call a custom function that will return the table name I want to use in my SQL syntax?

thanks in advance,
Bill
ALTER FUNCTION [GetTableName](@Criteria VARCHAR(1))
RETURNS varchar(50)
AS
BEGIN
DECLARE @Output varchar(50)
SET @Output = ''
 
SELECT @Output = 
CASE WHEN @Criteria = 'A' THEN 'TABLE_A'
WHEN @Criteria = 'B' THEN 'TABLE_B'
WHEN @Criteria = 'C' THEN 'TABLE_C'
END
 
RETURN @Output
END
 
 
 
Create PROCEDURE [dbo].[sp_TestStoreProc]
 SELECT TOP 1 * FROM + GetTableName('B') 
END

Open in new window

0
Comment
Question by:woyler
  • 2
3 Comments
 
LVL 60

Expert Comment

by:chapmandew
ID: 22618645
have to change your proc around bit:

Create PROCEDURE [dbo].[sp_TestStoreProc]
BEGIN
declare @x nvarchar(3000)
set @x = ' SELECT TOP 1 * FROM '+ GetTableName('B')
exec sp_executesql @x
END
0
 
LVL 60

Accepted Solution

by:
chapmandew earned 250 total points
ID: 22618653
also, have to include dbo. on your function call

Create PROCEDURE [dbo].[sp_TestStoreProc]
BEGIN
declare @x nvarchar(3000)
set @x = ' SELECT TOP 1 * FROM '+ dbo.GetTableName('B')
exec sp_executesql @x
END
0
 

Author Closing Comment

by:woyler
ID: 31502150
Perfect.  Thank you for the quick response.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

by Mark Wills PIVOT is a great facility and solves many an EAV (Entity - Attribute - Value) type transformation where we need the information held as data within a column to become columns in their own right. Now, in some cases that is relatively…
Introduction This article will provide a solution for an error that might occur installing a new SQL 2005 64-bit cluster. This article will assume that you are fully prepared to complete the installation and describes the error as it occurred durin…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used.

792 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question