How to pass date variable in open query? - sql

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..

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.

Related

Dates returned as columns in SQL Select

My user will submit a FromDate and a ToDate. What I want to happen is to select the dates that fall in between these dates, which I have accomplished with the script below. The dates will by dynamic.
DECLARE #fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE #toDateParam DATETIME = '2022-01-29 00:00:00.000'
;WITH fnDateNow(DayOfDate) AS
(
SELECT #fromDateParam AS TransactionDate
UNION ALL
SELECT DayOfDate + 1
FROM fnDateNow
WHERE DayOfDate < #toDateParam
)
SELECT fnDateNow.DayOfDate AS TransactionDate
FROM fnDateNow
This returns that dates as rows. What I am looking for is a way to make these dates return as the columns for a different script.
This table is called DailyTransactionHeader and it has a column [TransactionDate] and another one called [Amount].
There is the probability that their is not a DailyTransactionHeader with the specified Date for this I am looking to return 0.
So I am trying to have the data look like this (I formatted the date) There would be more than one row, but I just wanted to show an example of what I am trying to accomplish.
I appreciate any help,
Thanks
You can do it using dynamic sql. For example:
CREATE PROCEDURE [GET_DATE_TABLE]
(
#FROMDATE DATETIME,
#TODATE DATETIME
)
AS
DECLARE #PDATE DATETIME
DECLARE #SQL VARCHAR(MAX)
DECLARE #SEP VARCHAR(10)
SET #PDATE = #FROMDATE
SET #SQL = 'SELECT '
SET #SEP = ''
WHILE #PDATE < #TODATE
BEGIN
SET #SQL = #SQL + #SEP + 'NULL as [' + CONVERT(VARCHAR, CONVERT(DATE, #PDATE)) + ']'
SET #PDATE = #PDATE + 1
SET #SEP = ', '
END;
EXEC(#SQL)
Test Example:
DECLARE #fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE #toDateParam DATETIME = '2022-01-29 00:00:00.000'
exec dbo.GET_DATE_TABLE #fromDateParam, #toDateParam

OPENQUERY in SQL Server shows error

I am using linked server below query but it shows an error. Am I missing any quotes? Can anybody help me?
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 think you want something more like this:
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 >= CAST(''' + #fromdt + ''' as date) AND CAST(''' + #EndDate1 + ''' as date)
';

Conversion date error in SQL

When executing the below dynamic SQL statement, I get an error:
Conversion failed when converting date and/or time from character string
[ReturnDate] is defined as datetime and #FromDate and #ToDate parameters are being passed as type datetime as well. What am I missing ?
Set #SQLString =
'Select
[ID], [ReturnDate], [PolicyNumber]
From
Bil_ReturnsRepository
Where
(' + #PolicyNumber + ' is null or PolicyNumber = (' + #PolicyNumber + '))
and (ReturnDate) >= Convert(date, ' + #FromDate + '))
and (ReturnDate) <= Convert(date, ' + #ToDate + '))
and PaymentAmount > 0.00'
Presumably, you are using SQL Server. If so, learn to use sp_executesql. One of its powers is the ability to pass in parameters:
Set #SQLString = '
Select [ID], [ReturnDate], [PolicyNumber]
From Bil_ReturnsRepository
Where (#PolicyNumber is null or PolicyNumber = #PolicyNumber) and
(ReturnDate >= #p_FromDate) and
(ReturnDate <= #p_ToDate) and
PaymentAmount > 0.00
';
declare #p_fromdate date;
declare #p_todate date;
select #p_fromdate = convert(date, #fromdate),
#p_todate = convert(date, #todate);
exec sp_executesql #sql,
N'#p_fromdate date, #p_todate date, #policynumber int',
#p_fromdate=#p_fromdate, #p_todate=#p_todate, #policynumber=#policynumber;
The variables #p_fromdate and #p_todate are not necessary if #fromdate and #todate already have the correct types.
You cannot concatenate string with datetime, I would suggest you to
use sp_executesql to parameterize the dynamic sql
declare #SQLString nvarchar(max)--should be nvarchar
Set #SQLString =
'Select
[ID]
,[ReturnDate]
,[PolicyNumber]
From Bil_ReturnsRepository
Where
(#PolicyNumber is null or PolicyNumber = #PolicyNumber) and
ReturnDate >= #FromDate and
ReturnDate <= #ToDate and
PaymentAmount > 0.00'
exec sp_executesql #SQLString,
N'#FromDate datetime, #ToDate datetime, #PolicyNumber int',
#FromDate, #ToDate, #PolicyNumber
By this way your query is much safer and cleaner without so many string concatenation.
Note : use appropriate datatype for #PolicyNumber in sp_executesql

OpenQuery start and end date SQL

I am getting blank data while running query, and if i put manual date in criteria using only two '' then data is correct
DECLARE #strdate date,#endate date
set #strdate = '2017-06-24'
SEt #endate = '2017-06-26'
SELECT *
FROM Openquery(E2E,'Select
Order_Created_at,
Order_Number
,Shipping_Postcode
,Payment_Method
,Order_item
,Item_sku
,Item_Unit_Price
from sales_order_export_summary Where Date(Order_Created_at) >= '''' + #strdate + '''' AND Date(Order_Created_at) <= ''''+#endate + ''''')
you need to convert the date to string preferably in ISO format before concatenate
Where Date(Order_Created_at) >= ''' + convert(varchar(10), #strdate, 112) + ''' AND
If you want to use variables in OPENQUERY, you have to use dynamic SQL. I've changed variables #strdate and #enddate to varchar(10), because I wasn't able to concat strings.
DECLARE #strdate varchar(10),#endate varchar(10)
SET #strdate = '2017-06-24'
SET #endate = '2017-06-26'
DECLARE #SQL varchar(MAX) = '
SELECT *
FROM Openquery(E2E,''Select
Order_Created_at,
Order_Number
,Shipping_Postcode
,Payment_Method
,Order_item
,Item_sku
,Item_Unit_Price
from sales_order_export_summary Where Date(Order_Created_at) >= ''''' + #strdate + ''''' AND Date(Order_Created_at) <= '''''+#endate + ''''''')'
EXEC (#SQL)
Documentation for OPENQUERY.
Other answers explains the issue with format. Here is another easy way to do it but may not be efficient
DECLARE #strdate date,#endate date
set #strdate = '2017-06-24'
SEt #endate = '2017-06-26'
SELECT *
FROM Openquery(E2E, 'Select
Order_Created_at,
Order_Number
,Shipping_Postcode
,Payment_Method
,Order_item
,Item_sku
,Item_Unit_Price
from sales_order_export_summary')
WHERE Order_Created_at >= #strdate
AND Order_Created_at < Dateadd(dd, 1, #endate)

Dynamic sql syntax with dates

This line in my dynamic sql which feeds some dynamic pivoting, does not seem to take in the correct dates and return the expected results. The query runs and returns no results.
and PA.DATE_RECEIVED BETWEEN
'+ convert(varchar(10), #Startdate, 120) +' AND '+ convert(varchar(10), #Enddate, 120) +'
Check to see what values it is picking up ... Some sql in the stored procedure.
select convert(varchar(10), #Startdate, 120) - 2013-02-02
select convert(varchar(10), #Enddate, 120) - 2013-02-26
Running the query outside in normal sql, it works ? What is the problem.
select COALESCE( PT.[description] , 'Grand Total') AS [Transaction Type],
Sum (AI.PRICE_INC_VAT) AS [AMOUNT (รบ) CREDIT],
P.[DESCRIPTION] AS [PRODUCT TYPE]
From [dbo].[T1] C
join [dbo].[T2] S on S.[Customer_ID]=C.[Customer_ID]
join [dbo].[T3] SO on SO.[SITE_ID]=S.[SITE_ID]
join [dbo].[T4] OI on OI.[ORDER_ID]=SO.[SITE_ORDER_ID]
left join [dbo].[T5] P on P.[PRODUCT_ID]=OI.[PRODUCT_ID]
JOIN [dbo].[T6] AI ON AI.ORDER_ITEM_ID = OI.ORDER_ITEM_ID
JOIN T7 JBAI ON JBAI.ACTION_ITEM_ID = AI.ACTION_ITEM_ID
JOIN T8 JB ON JB.JOB_BATCH_ID = JBAI.JOB_BATCH_ID
JOIN T9 PA on PA.PAYMENT_ID=JB.PAYMENT_ID
LEFT JOIN T10 CU ON JB.CUSTOMER_USER_ID = CU.CUSTOMER_USER_ID
JOIN T11 PT ON PT.PAYMENT_TYPE_ID=PA.PAYMENT_TYPE_ID
LEFT JOIN T12 SU ON SU.SYS_USER_ID=JB.SYS_USER_ID
where P.[PRODUCT_CATEGORY_ID]= (
select PC.[PRODUCT_CATEGORY_ID] from [dbo].[PRODUCT_CATEGORY] PC
where PC.[DESCRIPTION]='BAGS')
and C.COMPANY_ID= '12'
and PA.DATE_RECEIVED BETWEEN '02-FEB-2013' AND '26-FEB-2013'
group by PT.DESCRIPTION, P.DESCRIPTION
You might be missing single quotes around dates, instead of PA.DATE_RECEIVED BETWEEN 2013-02-02 AND 2013-02-26 try to have the string read: PA.DATE_RECEIVED BETWEEN '2013-02-02' AND '2013-02-26'. Here is an example how you can get single quotes in string:
DECLARE #var VARCHAR(1000) =
'and PA.DATE_RECEIVED BETWEEN ''' +
convert(varchar(10), GETDATE(), 120) +
''' AND ''' +
convert(varchar(10), GETDATE(), 120) + ''''
SELECT #var
Single quote in a literal string is denoted by ''.
i think you got a quote problem. note the escaped quote to make a single quote appear in the dynamic query
and PA.DATE_RECEIVED BETWEEN
'''+ convert(varchar(10), #Startdate, 120) +''' AND '''+ convert(varchar(10), #Enddate, 120) +'''
Have you tried this :
and PA.DATE_RECEIVED BETWEEN #Startdate AND #Enddate
You don't have to convert the dates to make the BETWEEN statement work
I think there are a few of issues in your query, (1) forming up your sql string, (2) trying to compare date with varchar values and (3) converting string to date
For example it should be like;
declare #sql nvarchar(max),
#startdate varchar(50) = '20130202', --Using ISO format (yyyymmdd)
#enddate varchar(50) = '20130226' --Using ISO format
select #sql = 'SELECT col1, col2, ... FROM myTable WHERE mydate '+
'between convert(date, ' + #startdate + ') and ' +
'convert(date, ' + #enddate + ')'