Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Still working on indirection query
Message
From
05/02/2007 07:55:00
 
 
To
All
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Title:
Still working on indirection query
Environment versions
SQL Server:
SQL Server 2000
Miscellaneous
Thread ID:
01192348
Message ID:
01192348
Views:
67
Still battling the issue from last week on indiretion (macro).

Turns out I need to do double indirection. I need to get the list of columns I want (two out of many) from a lookup table, depending on parameters. Then, once I know the names of these two columns I need to get the actual data for them in one row.

I need to get the domestic or international benchmark and median values (bmk, mdn)

Something like this (simplified):
declare	@domestic 	INT
declare	@TypeId   	INT
set	@domestic=1		-- passed as parameter

DECLARE @Column2Get1	CHAR(20)
DECLARE @Column2Get2	CHAR(20)
DECLARE @Column2Get3	CHAR(20)
DECLARE @Column2Get4	CHAR(20)
SET @Column2Get3=''
SET @Column2Get4=''

DECLARE @sSQL NVARCHAR(500)
DECLARE @retval INT

IF @domestic=1
BEGIN
  set @Column2Get1='fname_dom_bmk'
  set @Column2Get2='fname_dom_mdn'
END
ELSE
BEGIN
  set @Column2Get1='fname_intl_bmk'
  set @Column2Get2='fname_intl_mdn'
END

-- Query #1 to get the names of the columns from SubTypes lookup table
SET @sSQL = N'SELECT table_w_data, @Column2Get3=' + @Column2Get1 + ', @Column2Get4=' + @Column2Get2 + CHAR(13)
SET @sSQL = @sSQL + 'FROM dbo.SubTypes ' + CHAR(13)
SET @sSQL = @sSQL + 'WHERE SubTypeId=' + CONVERT(char(2), @TypeId)
--select @sSQL   -- to test
EXECUTE sp_executesql @sSQL

-- Query #2 to get the values of the desired columns from Benchmarks lookup table (simplified WHERE clause from original)
-- table (simplified): ItemId (Int), DomC2SBmk (Int), DomC2SMdn (Int), IntlC2SBmk (Int), IntlC2SMdn (Int), ...

SET @sSQL = N'SELECT ' + @Column2Get3 + ',' + @Column2Get4 + CHAR(13)
SET @sSQL = @sSQL + 'FROM dbo.Benchmarks ' + CHAR(13)
SET @sSQL = @sSQL + 'WHERE (ItemId=5) '
Questions:

Query #1 fails on syntax even though it seems correct to me ("Must declare the variable '@Column2Get3'.").
How do I get the values returned for names of columnns (Columnn2Get1, Column2Get2)?

Query #2: How do I build it to use the returned column names (out of the many possible columns in that table)?

TIA


Alex Feldstein, MCP, Microsoft MVP
VFP Tips: English - Spanish
Website - Blog - Photo Gallery


"Once again, we come to the Holiday Season, a deeply religious time that each of us observes, in his own way, by going to the mall of his choice." -- Dave Barry
Next
Reply
Map
View

Click here to load this message in the networking platform