OpenQuery start and end date SQL - 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)

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

How to pass date variable in open query?

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.

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

Getting Datetime by Year, Month, Date

I want to get date by Using Year, Month and Day functions. Example
declare #Date smalldatetime
select #Date = Year('20140530') + Month('20140530') + Day('20140530')
What I want is to assign #Date = '20140530' as smalldatetime. But I want to do this by means of somwething similar to above expression. How can Ido this. Thanks in advance.
Instead try something like below
declare #Date varchar(20)
select #Date = cast(Year('20140530') as varchar) +
cast(Month('20140530') as varchar) +
cast(Day('20140530') as varchar)
select #Date
results in: 2014530.
(OR) like below
declare #Date VARCHAR(20)
select #Date = cast(Year('20140530') as varchar) + '-' +
cast(Month('20140530') as varchar) + '-' +
cast(Day('20140530') as varchar)
select cast(#Date as smalldatetime)
results in: 2014-05-30 00:00:00
Year()/Month()/DaY() functions returns the year/Month/Day as Integer. What you are actually doing can be simulated as below
declare #Date smalldatetime
set #Date = 2049
select #Date
which will result in : 1905-08-12 00:00:00
Use Like, Set will give the Date in #Date instead of select
declare #Date smalldatetime
set #Date = Year('20140530') + Month('20140530') + Day('20140530')
print #Date

SQL date selection as NULL, After, Before, Between

Requirement: select by date as After, Before, Between or all if null
I'm using SQL Server 2008
This is my attempt but I'm getting syntax errors on code that is valid used outside of the case.
Is there a better method?
using case what is the correct syntax?
declare #StartDate datetime;
declare #EndDate datetime;
SET #EndDate = GETDATE();
SET #StartDate = DATEADD(year, -2, GETDATE());
select *
from ArCustomer
where CAST(Customer as int) > 1000
AND
CASE WHEN #StartDate IS NOT NULL AND #EndDate IS NOT NULL THEN
ArCustomer.DateLastSale BETWEEN #StartDate AND #EndDate
WHEN #StartDate IS NULL AND #EndDate IS NOT NULL THEN
ArCustomer.DateLastSale < #EndDate
WHEN #StartDate IS NOT NULL AND #EndDate IS NULL THEN
ArCustomer.DateLastSale > #StartDate
END;
Alternately, you could not restrict by the date parameter if it is NULL:
SELECT *
FROM ArCustomer ac
WHERE
CAST(ac.Customer as int) > 1000
AND (ac.DateLastSale >= #StartDate OR #StartDate IS NULL)
AND (ac.DateLastSale <= #EndDate OR #EndDate IS NULL)
Or... you can handle the NULL by treating it as the low-end or high-end date:
SELECT *
FROM ArCustomer ac
WHERE
CAST(ac.Customer as int) > 1000
AND ac.DateLastSale BETWEEN ISNULL(#StartDate, '1900-01-01')
AND ISNULL(#EndDate, '9999-12-31')
EDIT:
There could be a difference in the execution plan between these two approaches, so you might try both methods and see if one out-performs the other...
WHERE CAST(Customer as int) > 1000 AND
(#StartDate IS NULL OR #StartDate <= ArCustomer.DateLastSale) AND
(#EndDate IS NULL OR ArCustomer.DateLastSale <= #EndDate)
Please note that the below query should have * avoided and the specific column names should be mentioned.
declare #StartDate datetime;
declare #EndDate datetime;
SET #EndDate = GETDATE();
SET #StartDate = DATEADD(year, -2, GETDATE());
Declare #SQL Varchar(1000)
Set #SQL = 'select ColumnName
from ArCustomer
where CAST(Customer as int) > 1000
AND'
if(#StartDate IS NOT NULL AND #EndDate IS NOT NULL)
Begin
Set #SQL = #SQL + ' ArCustomer.DateLastSale BETWEEN ''' + Convert(varchar, #StartDate) +
''' AND ''' + Convert(varchar, #EndDate) + ''''
End
else if(#StartDate IS NULL AND #EndDate IS NOT NULL)
Begin
Set #SQL = #SQL + ' ArCustomer.DateLastSale < ''' + Convert(varchar, #EndDate) + ''''
End
else
Set #SQL = #SQL + ' ArCustomer.DateLastSale > ''' + Convert(varchar, #StartDate) + ''''
exec(#SQL)
Considered all cases.