0

I try to pass date variable in open query but it shows error like

"Incorrect syntax near + "

Here is my query:

DECLARE @fromdt DATETIME = '2018-04-07';
 DECLARE @EndDate1 DATETIME = '2018-04-07';
    Select * from openquery(TIMEV,
       'SELECT REPLACE(LTRIM(REPLACE(badgenumber,"0"," "))," ","0") badgenumber,
checktime as dt
from checkinout a 
join USERINFO c on c.userid=a.userid  
        WHERE checktime >= '''''+CONVERT(CHAR(10), @fromdt, 120)+'''''  AND ''''' + CONVERT(CHAR(10), @EndDate1, 120) + ''''' ')

I am stuck here .Thanks in advance..

4
  • Have you tried manipulating the date parameters in a separate command? You should be able to pass the parameters in rather than using dynamic sql Commented Apr 8, 2018 at 6:04
  • To clarify a bit, set @param = convert(@param...) Commented Apr 8, 2018 at 6:06
  • @LJ01 - this wouldn't help because the OPENQUERY documentation explicitly forbids using any variables. So it's not a problem of converting, it's a problem of any variable being passed to it. Should be remedied, though, with something like in my answer. The provided link has multiple workarounds for this. Commented Apr 8, 2018 at 7:10
  • Sorry, I'm still not seeing any point in using openquery at all. Is there something in there that can't be done using a standard query? Commented Apr 8, 2018 at 8:02

1 Answer 1

2

OPENQUERY documentation explicitly says:

OPENQUERY does not accept variables for its arguments.

Therefore, using a trick from this site you should be able to do it like this:

DECLARE @fromdt DATETIME = '2018-04-07';
DECLARE @EndDate1 DATETIME = '2018-04-07';

DECLARE @query nvarchar(max) = 
'SELECT * FROM OPENQUERY(TIMEV,
    '' SELECT REPLACE(LTRIM(REPLACE(badgenumber,"0"," "))," ","0") badgenumber,
       checktime AS dt
       FROM checkinout a 
         JOIN USERINFO c on c.userid=a.userid  
       WHERE checktime >= ''''' + CONVERT(CHAR(10), @fromdt, 120) + '''''  AND ''''' + CONVERT(CHAR(10), @EndDate1, 120) + ''''' ''
)';

EXEC(@query);

EDIT: there are also two other methods suggested in the link I provided above the code snippet if you wish to try them out.

Sign up to request clarification or add additional context in comments.

1 Comment

I successfully adapted this approach (but using 121 as the CONVERT style).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.