0

I have the following stored procedure that returns a row on a table, which I then want to input into an SQL statement as a table name.

Stored Procedure:

Create Procedure TLookup as
select distinct [BillingReferenceData].[dbo].[Customers].[Tariff]
from [daisybilling].[dbo].[APRW14_FFA68878_Calls]
inner join [BillingReferenceData].[dbo].[Customers] on [DaisyBilling].[dbo].[APRW14_FFA68878_Calls].[Customer Lookup] = [BillingReferenceData].[dbo].[Customers].[Customer ID]
where [DaisyBilling].[dbo].[APRW14_FFA68878_Calls].[Customer Lookup] = [BillingReferenceData].[dbo].[Customers].[Customer ID]

Here is the remainder of my code, I have highlighted "INSERT TABLE NAME HERE" where I need to input the table name collected in the above procedure.

UPDATE [APRW14_FFA68878_Calls] 
SET    [APRW14_FFA68878_Calls].[Sell Price] = [INSERT TABLE NAME HERE].[Peak]/60*[APRW14_FFA68878_Calls].[Duration (secs)]
FROM   [Test].[dbo].[DaisyRates_May2014]
INNER JOIN [DaisyBilling].[dbo].[APRW14_FFA68878_Calls] on [DaisyBilling].[dbo].[APRW14_FFA68878_Calls].[ChargeCode] = [Test].[dbo].[INSERT TABLE NAME HERE].[Chargecode]

What is the correct syntax in order to achieve this?

Thanks

user3580480
  • 442
  • 7
  • 14
  • 45
  • 1
    Unrelated but you should learn about aliases. They'd make your query much easier to read. e.g. instead of `SELECT db.dbo.table.column FROM db.dbo.table` use `SELECT t.column FROM db.dbo.table AS t` – OGHaza May 27 '14 at 14:25

1 Answers1

0

Once you have assigned the result of the stored procedure (the table name) to a variable, you'll have to use dynamic sql to insert it into your update statement, like this:

DECLARE @sql NVARCHAR(max)

SELECT @sql = 'UPDATE [APRW14_FFA68878_Calls] 
SET    [APRW14_FFA68878_Calls].[Sell Price] = ' + @tablename + '.[Peak]/60*[APRW14_FFA68878_Calls].[Duration (secs)]
FROM   [Test].[dbo].[DaisyRates_May2014]
INNER JOIN [DaisyBilling].[dbo].[APRW14_FFA68878_Calls] on [DaisyBilling].[dbo].[APRW14_FFA68878_Calls].[ChargeCode] = [Test].[dbo].[INSERT TABLE NAME HERE].[Chargecode]'

EXEC sp_executesql @sql
Dave.Gugg
  • 6,561
  • 3
  • 24
  • 43