Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 12890

Dynamic SQL Question

$
0
0
CREATE TABLE [Reference].[CRKAttr](
	[CRKID] [int] IDENTITY(1,1) NOT NULL,
	[Client] [varchar](100) NULL,
	[AttrOrder] [int] NULL,
	[AttrTable] [varchar](100) NULL,
	[Attr] [varchar](100) NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING ON
GO
SET IDENTITY_INSERT [Reference].[CRKAttr] ON

INSERT [Reference].[CRKAttr] ([CRKID], [Client], [AttrOrder], [AttrTable], [Attr]) VALUES (1, N'Brampton', 1, N'UPPOREP', N'pogucd')
INSERT [Reference].[CRKAttr] ([CRKID], [Client], [AttrOrder], [AttrTable], [Attr]) VALUES (2, N'Brampton', 2, N'UPPNREP', N'pougty')

SET IDENTITY_INSERT [Reference].[CRKAttr] OFF
CREATE TABLE [ETL].[Source](
	[SourceID] [int] IDENTITY(1,1) NOT NULL,
	[SourceName] [varchar](100) NOT NULL,
	[SourceDBName] [varchar](100) NOT NULL,
	[SourceServerName] [varchar](100) NOT NULL,
	[Process] [char](1) NOT NULL DEFAULT ('Y'),
	[ClientSourceID] [int] NULL,
	[ClosingPeriod] [varchar](6) NULL,
	[DMDBName] [varchar](100) NULL,
	[DMServer] [varchar](100) NULL,


INSERT [ETL].[Source] ([SourceID], [SourceName], [SourceDBName], [SourceServerName], [Process], [ClientSourceID], [ClosingPeriod], [DMDBName], [DMServer]) VALUES (3, N'Brampton', N'Cognos - Brampton (LIVE)', N'xxxx', N'Y', 3, N'200301', N'abcd', N'xxxx')

Hi All

I have the above table creation statement and have a problem.

Imagine that this client has 2 "AttrTables" but another client could have 3 or 4

I need to dynamically generate a SQL Statement which will do the selection for me with the associated join.

The output I need is:

Select distinct U1.pogucd, U2.pougty FROM [Cognos - Brampton (LIVE)].dbo.UPPOREP U1 CROSS JOIN [Cognos - Brampton (LIVE)].dbo.UPPNREP U2
I need the Client from table A to pull the DB name from table B and insert that as part of the generated output.

I tried to create the statement but ended up getting frustrated with it, the reason is that the fields it picks up from differ between each client, i provided the easiest one here as it only has 2

Another client may have 3 tables and 3 different columns or even more

Does anyone know how to achieve what i'm looking to do? the alias names come from the first character of the AttrTable + Convert(varchar,AttrID) as the alias name for each column

Thanks and as always any help would be much appreciated :)

One last thing a nice ot have but not completely necessary - if theres a way to actually just do this selection instead of outputting the sql query i'd love to know both ways just for learning purposes

J




Viewing all articles
Browse latest Browse all 12890

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>