SQL Servre:在openquery中使用datetime变量

时间:2019-02-04 15:43:37

标签: sql-server postgresql tsql linked-server

我尝试在SQL Server环境中的Postgres服务器上的链接服务器查询中发送DATETIME变量。

我的代码:

DECLARE @start_date DATETIME;
SET @start_date ='2019-02-01';

SELECT *
FROM OPENQUERY (postgresDB, 'SELECT id, action_time
                             FROM call_history
                             WHERE action_time > ''' + @start_date + ''' ')

我尝试在变量周围使用不同数量的引号进行试验,但始终会遇到此错误:

  

“ +”附近的语法不正确

1 个答案:

答案 0 :(得分:0)

将日期时间转换为用于连接的字符串,或者将@startdate声明为nvarchar或varchar。

当我尝试选择您的字符串时:

DECLARE @start_date datetime;
SET @start_date ='2019-02-01';

select 'SELECT
                    id,
                    action_time
                FROM call_history
                WHERE action_time > ''' + @start_date + '''
        '

我得到:

Msg 241, Level 16, State 1, Line 4
Conversion failed when converting date and/or time from character string.

但这很好用:

DECLARE @start_date nvarchar(10);
SET @start_date ='2019-02-01';

select 'SELECT
                    id,
                    action_time
                FROM call_history
                WHERE action_time > ''' + @start_date + '''
        '