Friday, March 23, 2012

Help on dynamic sql results on temp table

The dynamic sql is used for link server. What I need is that the result of the dynamic sql put on a temp table. Can someone help. Im getting an error

CREATE PROCEDURE GSCLink

( @.LinkCompany nvarchar(50), @.Page int, @.RecsPerPage int )

AS

SET NOCOUNT ON

--Create temp table

CREATE

TABLE #TempTable

( ID int IDENTITY, Name nvarchar(50), AccountID int, Active bit )

INSERT INTO #TempTable (Name, AccountID, Active)

--dynamic sql

DECLARE @.sql nvarchar(4000)

SET @.sql = 'SELECT a.Name, a.AccountID, a.Active

FROM CRMSBALINK.' + @.LinkCompany + '.dbo.AccountTable a

LEFT OUTER JOIN CRM2OA.dbo.GSCCustomer b

ON a.AccountID = b.oaAccountID

WHERE oaAccountID IS NULL

ORDER BY Name ASC'

EXEC sp_executesql @.sql

--Find out the first and last record

DECLARE @.FirstRec int

DECLARE @.LastRec int

SELECT @.FirstRec = (@.Page - 1) * @.RecsPerPage

SELECT @.LastRec = (@.Page * @.RecsPerPage + 1)

--Return the set of paged records, plus an indication of more records or not

SELECT *, (SELECT COUNT(*) FROM #TempTable TI WHERE TI.ID >= @.LastRec) AS MoreRecords

FROM #TempTable

WHERE ID > @.FirstRec AND ID < @.LastRec

Error:

Msg 156, Level 15, State 1, Procedure GSCLink, Line 22

Incorrect syntax near the keyword 'DECLARE'.

change your dynamic sql as follow as ..

SET @.sql = 'Insert Into #TempTable SELECT a.Name, a.AccountID, a.Active

FROM CRMSBALINK.' + @.LinkCompany + '.dbo.AccountTable a

LEFT OUTER JOIN CRM2OA.dbo.GSCCustomer b

ON a.AccountID = b.oaAccountID

WHERE oaAccountID IS NULL

ORDER BY Name ASC'

|||Error gone... But when I ran the sprocs... No records on the temp table. Do you think I need to catch the results on the dynamic sql? How can I do that? Thanks|||

Is your link server is CRMSBALINK. Pls verify the output of SQL query alone ..

|||I got it... Thanks|||yup its CRMSBALINK. But I got it working now... Thanks anyway

No comments:

Post a Comment