I am trying to use dynamic sql to get a cursor. But I got some funny syntax problems. Hope someone could explain to me.if I run the following code, I got the following error:Msg 102, Level 15, State 1, Line 26Incorrect syntax near 'select * from MISTY_OWNER.MISTY_F_STC_EXECUTIONS where transactiondateid=20110509 AND DistributionId='121028286'.DECLARE @EXTRACTDATE VARCHAR(30);SET @EXTRACTDATE='20110509'; --2011-05-09DECLARE @OPENQUERY VARCHAR(500);-- -- Portfolio,SET @OPENQUERY = ' DECLARE RECORD_CURSOR CURSOR FOR SELECT TransactionDateId, TransactionType, TradeDate, ExecutionId, DistributionId, product, Moniker, SettlementDate, Symbol, Cusip, Side, Price, Quantity, ExecutingBroker, ExecutionTime, Source, Destination, Service, OrderType, HardCommission, SoftCommission, GrossCredit from openquery( DBWH_US_PROD, ''select * from MISTY_OWNER.MISTY_F_STC_EXECUTIONS where transactiondateid=' + @EXTRACTDATE + ' AND DistributionId=''''121028286'''' '')'; --from openquery( DBWH_US_PROD, ''select * from MISTY_OWNER.MISTY_F_STC_EXECUTIONS where DistributionId=''''121028286'''''')';EXEC(@OPENQUERY)DEALLOCATE RECORD_CURSOR
But if I just Move 'DECLARE RECORD_CURSOR CURSOR FOR ' from the @OPENQUERY into the EXEC, it works fine....DECLARE @EXTRACTDATE VARCHAR(30);SET @EXTRACTDATE='20110509'; --2011-05-09DECLARE @OPENQUERY VARCHAR(500);-- -- Portfolio,SET @OPENQUERY = ' SELECT TransactionDateId, TransactionType, TradeDate, ExecutionId, DistributionId, product, Moniker, SettlementDate, Symbol, Cusip, Side, Price, Quantity, ExecutingBroker, ExecutionTime, Source, Destination, Service, OrderType, HardCommission, SoftCommission, GrossCredit from openquery( DBWH_US_PROD, ''select * from MISTY_OWNER.MISTY_F_STC_EXECUTIONS where transactiondateid=' + @EXTRACTDATE + ' AND DistributionId=''''121028286'''' '')'; --from openquery( DBWH_US_PROD, ''select * from MISTY_OWNER.MISTY_F_STC_EXECUTIONS where DistributionId=''''121028286'''''')';EXEC('DECLARE RECORD_CURSOR CURSOR FOR ' + @OPENQUERY)DEALLOCATE RECORD_CURSOR