带有参数的带有OPENQUERY的exec存储过程

时间:2013-07-23 11:11:35

标签: sql-server stored-procedures openquery

我有以下程序:

CREATE PROCEDURE [dbo].[meals] @EncounterID nvarchar(15), @EventDate nvarchar(30)
AS
   DECLARE @TSQL varchar(8000);

   SELECT  @TSQL = 'SELECT * FROM OPENQUERY(cerner, ''select ce.result_val  PercentEaten,
ce.event_cd Meal
 from clinical_event ce
 where
 ce.task_assay_cd in ( 5362408, 5362296, 5361870)
 and ce.event_end_dt_tm >= sysdate-30
 and ce.event_cd in (636033, 636036, 636039)
 and ce.event_class_cd = 233
and ce.encntr_id = ''' +CAST(@EncounterID as varchar(15))+ '''
and ce.event_end_dt_tm between to_char('''+CAST(@EventDate as varchar(30))+''' - .5) and 
    to_char('''+CAST(@EventDate as varchar(30))+''' - 1)
'')';
EXEC (@TSQL);
GO

当我用这一行执行时:

exec dbo.meals @EncounterID =  '12345678',@EventDate = '07/18/2013'

我收到的错误只是error at line 9

我做错了什么?

1 个答案:

答案 0 :(得分:0)

从评论我可以得出以下结论:

  1. 检查cerner侧是否确实有to_char()函数。如果你没有它,那就是错误。
  2. 取而代之的是CAST(@EventDate as varchar(30)),请尝试将其转换为CONVERT(varchar(30), @EventDate, 111)(如果您还需要时间,请将 111 更改为 120
  3. 修改

    显然你必须在openquery中使用Oracle语法。它应该像... ...

    AND ce.event_end_dt_tm between to_date ('2013/01/01', 'yyyy/mm/dd') and to_date ('2013/12/31', 'yyyy/mm/dd')
    

    因此,第2点应该是你的解决方案,有一些不同的Oracle函数调用。

    完整的AND条款:

    ...
    and ce.event_end_dt_tm between to_date(''' + CONVERT(varchar(30), @EventDate, 111) + ''', ''yyyy/mm/dd'') - 1 and to_date(''' + CONVERT(varchar(30), @EventDate, 111) + ''', ''yyyy/mm/dd'') - 0.5
    

    注意:我不明白这些日期是否有意义,所以我将的顺序从转换为日期。< / p>