无法在链接服务器(DB2)中使用参数执行打开查询

时间:2017-10-16 02:57:18

标签: sql db2 linked-server

下面是一个简单的查询,用于从本地数据库获取值并从DB2链接服务器中选择值。我无法执行它。我收到了一个错误。

Incorrect syntax near 'AU000'.

如果我像exec(@VAR)一样独立运行查询,它可以工作,但Exec(@TSQL)却没有。请帮忙。下面是我正在运行的查询。

DECLARE @TSQL varchar(8000) , @VAR char(200)          
      select  @VAR = 'select top 1 ''AU000'' +  CONVERT(VARCHAR(50),CPHN#)  from upload.cancelledcontractheader'    
      SELECT  @TSQL = '   
      SELECT * FROM OPENQUERY(    
      AS400TS_LNK,    
      ''
      select * from TWGTEST.AUPRDDBF.CONTACCT  where ACTRNO ='''''+@VAR+'''''   
      ''
      )   
      '
      EXEC (@TSQL)

最后我想实现这个

     DECLARE @TSQL varchar(8000) , @VAR char(200)         

Create table #siteId (id varchar(100))
DECLARE @SQL nvarchar(max) = N'insert into #siteId (id) select (''AU000'' +  CONVERT(VARCHAR(50),CPHN#))  from upload.cancelledcontractheader'
exec (@SQL)

 select  @VAR = 'select ''AU000'' +  CONVERT(VARCHAR(50),CPHN#)  from upload.cancelledcontractheader'   
              SELECT  @TSQL = '   
              SELECT * FROM OPENQUERY(    
              AS400TS_LNK,    
              ''
              insert into AUPRDDBF.CONTACCT (ACTRNO,    ASEQN,  ACTRAL, ASEQA,  ATYPECOD,   ASKU,   AACDTID,    AACCTVR,    ACDTIDD,    AACCTCD,    ASTATUS,    AAMOUNT,    ACRTUSR,    ACRTDTE,    ACRTTIM,    ACHGUSR,    ACHGDTE,    
    ACHGTIM)
    SELECT ACTRNO,  ASEQN,  ACTRAL, ASEQA,  '9123', ASKU,   AACDTID,    AACCTVR,    ACDTIDD,    AACCTCD,    'C',    AAMOUNT,    ACRTUSR,    ACRTDTE,    ACRTTIM,    'SSCE2',    ACHGDTE,    
    ACHGTIM
    from AUPRDDBF.CONTACCT where ACTRNO in '''''+#siteId+'''''   
              ''
              )   
              '
              EXEC (@TSQL)
drop table #siteId

0 个答案:

没有答案