Friday, March 9, 2012

Help using dynamic queries in temp table

The dynamic sql is used for link server. Can someone help. Im getting an error

CREATEPROCEDURE GSCLink

(

@.LinkCompanynvarchar(50),@.Pageint,@.RecsPerPageint)

AS

SET

NOCOUNTON

--Create temp table

CREATE

TABLE #TempTable

(

IDintIDENTITY,Companynvarchar(50),AcctIDint,IsActivebit)

INSERT

INTO #TempTable(Name, AccountID, Active)

--dynamic sql

DECLARE

@.sqlnvarchar(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

@.FirstRecint

DECLARE

@.LastRecint

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

*,(SELECTCOUNT(*)FROM #TempTable TIWHERE TI.ID>= @.LastRec)AS MoreRecords

FROM

#TempTable

WHERE

ID> @.FirstRecAND ID< @.LastRec

Error:

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

Incorrect syntax near the keyword 'DECLARE'.

Here is the problem:

INSERT

INTO #TempTable(Name, AccountID, Active)

It could be something like this:

INTO #TempTable values('Name', 'AccountID', 'Active')

or INTO #TempTable values(@.Name, @.AccountID, @.Active) (if those variables are defined)

or ...

Hope it helps.

|||Isnt the result of the dynamic sql put on the temp table automatically? If not... how can I capture the results of the dynamic sql?|||I got it working... Thanks anyway

No comments:

Post a Comment