Hello,
I am trying to create a stored procedure that pulls data from a linked server. I've done this succesfully multiple times before but I've never had to do it to a nested query and I've tried for a really long time and can't seem to get the syntax correct. Any suggestions would be greatly appreciated! Here is the syntax I'm using:
I am trying to create a stored procedure that pulls data from a linked server. I've done this succesfully multiple times before but I've never had to do it to a nested query and I've tried for a really long time and can't seem to get the syntax correct. Any suggestions would be greatly appreciated! Here is the syntax I'm using:
Code:
@BeginDate VarChar(12),
@EndDate VarChar(12)
AS
BEGIN
declare @sql varchar(max)
set @sql='
SELECT Site,
LogDate,
Item,
Qty,
Val,
Amt
FROM OPENQUERY
(
LinkedServerName, ''
B.STATS.SITE as Site,
B.STATS.LOGDATE as LogDate,
B.ITEMS.ITEM as Item,
B.ITEMS.QTY as Qty,
B.ITEMS.VAL as Val,
B.ITEMS.AMT as Amt
From
(
SELECT STATS.SITE,
STATS.SALEID,
STATS.LOGDATE,
ITEMS.ITEM,
ITEMS.QTY,
ITEMS.VAL,
ITEMS.AMT
FROM STATS INNER JOIN ITEMS ON (STATS.SALEID = ITEMS.SALEID) AND (STATS.SITE = ITEMS.SITE)
WHERE (STATS.LOGDATE BETWEEN (''''' + CONVERT(char(10), @BeginDate, 101) + ''''') AND (''''' + CONVERT(char(10), @EndDate, 101) + ''''') )
AND items.item = ''''721134''''
) A
,
(
SELECT STATS.SITE as Site,
STATS.SALEID as SaleID,
STATS.LOGDATE as LogDate,
ITEMS.ITEM as Item,
ITEMS.QTY as Qty,
ITEMS.VAL as Val,
ITEMS.AMT as Amt
FROM STATS INNER JOIN ITEMS ON (STATS.SALEID = ITEMS.SALEID) AND (STATS.SITE = ITEMS.SITE)
WHERE (STATS.LOGDATE BETWEEN (''''' + CONVERT(char(10), @BeginDate, 101) + ''''') AND (''''' + CONVERT(char(10), @EndDate, 101) + ''''') )
)B
Where
A.Site = B.site and A.Saleid = B.saleid
'')'
Exec(@sql)
END