TSQL -- Inserting Dates Into Dynamic SQL - tsql

Consider the following TSQL:
SET #WhereClause1 = 'where a.Date > ' + #InvoiceDate
I get a date/string conversion error. #InvoiceDate is a datetime variable. What is the right syntax?

This might work.
SET #WhereClause1 = 'where a.Date > ''' + convert(varchar, #InvoiceDate) + ''''
although an error will be raised if the value is null.

This will work:
SET #WhereClause1 = 'where a.Date > ''' + cast(#InvoiceDate as varchar(100)) + ''''

Since your composing query as a string first, then I think you need to convert #InvoiceDate to a string with something like this. http://www.databasejournal.com/features/mssql/article.php/10894_2197931_1/Working-with-SQL-Server-DateTime-Variables-Part-Two---Displaying-Dates-and-Times-in-Different-Formats.htm

... and you will probably need to enclose date strings in quotes.
It would probably actually be better to construct the date string in the calling routine because you should be checking there for null values and maybe other validations.

EXEC sp_executesql N'SELECT * FROM Orders WHERE a.Date > #date',
N'#date datetime',
#date = #InvoiceDate

Related

Data factory Postgres query date time error

I have a postgressql query. I tried it in db query and it seems to work fine. But in data bricks its not working as expected.
I have to use where clause. Where I am extracting date from timestamp and comparing it with passed value (which is in date time format). I am extracting date and checking if its less than the one from timestamp.
Pls check in the WHERE clause.
select DATE(to_timestamp(time,'YYYY-MM-DD %H24:%m:%s' )) as modifiedtime, *
FROM testg
WHERE DATE(to_timestamp(time,'YYYY-MM-DD %H24:%m:%s' )) >= DATE(to_timestamp('2020-10-25 00:00:00','YYYY-MM-DD %H24:%m:%s' )) - INTERVAL '7 DAY'
order by time asc
In data factory the query looks like:
#concat('select * FROM streamingData WHERE property_name = ''', item(), '''' ,' AND DATE(to_timestamp(''', activity('Lookup1').output.firstRow.max_timestamp, '''',',''','YYYY-MM-DD %H24:%m:%s', ''' ))' ,' >= ''', 'DATE(to_timestamp(''', pipeline().parameters.enddate, '''',',''','YYYY-MM-DD %H24:%m:%s', ''' ))' )
Data:
time:
"2020-10-25 13:00:22.000000+01"
"2020-10-24 14:00:22.000000+01"
"2020-10-25 12:00:22.000000+01"
"2020-10-26 01:00:22.000000+01"
and I am using trigger().outputs.windowEndTime() -
output is: 2020-10-20 01:00:22
I am comparing both the date values i.e.
If 2020-10-26 >= 2020-10-20
Even after filtering, i get all the data i.e. also the dates from 2019 etc.
What am I missing.
Strangely I tried the comparison using Between (which was not working) and I was still getting all the years even after filtering.
Methods used :
Used between clause - was not working
Used <= and >= - was also not working.
I used later "SYMMETRIC" function. with between - with which the filter worked. I suppose in BETWEEN SYMMETRIC the arguments are automatically swapped and that a nonempty range is always implied.
at the end the query is like:
#concat('select * FROM streamingData WHERE property_name = ''', item(), '''' ,' AND time BETWEEN SYMMETRIC to_timestamp(''', activity('LKP_RMS_ValueStream_Time').output.firstRow.max_timestamp, '''',',''','YYYY-MM-DD', ''' )' ,' AND ', 'to_timestamp(''', pipeline().parameters.enddate, '''',',''','YYYY-MM-DD', ''' )' , ' - ', 'INTERVAL ''', '7 DAY', '''' )
Thanks for the time and help.

SQL RIGHT function not working as expected

I'm trying to extract the month number from a date as a left padded string with 0's.
So, for example, from '2018-01-31' I want the string '01'.
Currently I have this:
SELECT RIGHT('0' + CAST(MONTH('2018-01-31') AS CHAR(2)), 2)
Which is returning '1' but I would have expected it to return '01' because I've provided the second argument to RIGHT as 2.
Could someone explain why this isn't working as I think it should?
You need to change CHAR to VARCHAR:
SELECT RIGHT('0' + CAST(MONTH('2018-01-31') AS VARCHAR(2)), 2)
db<>fiddle demo
CHAR(2) is blank padded so you get RIGHT('01 ',2) which is '1 '.
You could use FORMAT instead, when you first cast the string to a DATE type.
SELECT FORMAT(CAST('2018-01-31' as DATE),'MM')
As for why that SQL with the right didn't work?
Try this SQL and notice the difference (the extra space):
SELECT quotename('0' + CAST(1 AS CHAR(2))), quotename('0' + CAST(1 AS VARCHAR(2)))

Frontbase date formatting functions

I've searched all over and can't find any info in Frontbase documentation or, for that matter, SQL92-related docs...does Frontbase have functions equivalent to datepart/date_part, or date_format as found in other RDBMSes? I need to output a timestamp column as a formatted string, and the correct syntax for Frontbase eludes me.
There may be a better way to do it, but a combination of cast, extract and string concatenation gave me the desired result:
SELECT CAST(EXTRACT(month FROM mytimestampcol) AS VARCHAR(2)) || '/' || CAST(EXTRACT(day FROM mytimestampcol) AS VARCHAR(2)) || '/' || CAST(EXTRACT(year FROM mytimestampcol) AS VARCHAR(4)) AS "Begin Date" FROM mytable
Yields "mm/dd/yyy" formatting.
One of many SQL92 function references: http://www.faircom.com/doc/sqlref/#12959.htm

Sum like operation for strings in t-sql

I already have query to concatenate
DECLARE #ids VARCHAR(8000)
SELECT #ids = COALESCE(#ids + ', ', '') + concatenatedid
FROM #HH
but if I have to do it inline how can I do that? Any help please.
SELECT sum(quantity), COALESCE(#ids + ', ', '') + concatenatedid from #HH
Thanks.
Use the XML PATH trick. You may need a CAST
SELECT
SUBSTRING(
(
SELECT
',' + concatenatedid
FROM
#HH
FOR XML PATH ('')
)
, 2, 7999)
Also:
Join characters using SET BASED APPROACH (Sql Server 2005)
Subquery returned more than 1 value

DESCENDING/ASCENDING Parameter to a stored procedure

I have the following SP
CREATE PROCEDURE GetAllHouses
set #webRegionID = 2
set #sortBy = 'case_no'
set #sortDirection = 'ASC'
AS
BEGIN
Select
tbl_houses.*
from tbl_houses
where
postal in (select zipcode from crm_zipcodes where web_region_id = #webRegionID)
ORDER BY
CASE UPPER(#sortBy)
when 'CASE_NO' then case_no
when 'AREA' then area
when 'FURNISHED' then furnished
when 'TYPE' then [type]
when 'SQUAREFEETS' then squarefeets
when 'BEDROOMS' then bedrooms
when 'LIVINGROOMS' then livingrooms
when 'BATHROOMS' then bathrooms
when 'LEASE_FROM' then lease_from
when 'RENT' then rent
else case_no
END
END
GO
Now everything in that SP works but I want to be able to choose whether I want to sort ASCENDING or DESCENDING.
I really can't fint no solution for that using SQL and can't find anything in google.
As you can see I have the parameter sortDirection and I have tried using it in multiple ways but always with errors... Tried Case Statements, IF statements and so on but it is complicated by the fact that I want to insert a keyword.
Help will be very much appriciated, I have tried must of the things that comes into mind but haven't been able to get it right.
You could use two order by fields:
CASE #sortDir WHEN 'ASC' THEN
CASE UPPER(#sortBy)
...
END
END ASC,
CASE #sortDir WHEN 'DESC' THEN
CASE UPPER(#sortBy)
...
END
END DESC
A CASE will evaluate as NULL if none of the WHEN clauses match, so that causes one of the two fields to evaluate to NULL for every row (not affecting the sort order) and the other has the appropriate direction.
One drawback, though, is that you'd need to duplicate your #sortBy CASE statement. You could achieve the same thing using dynamic SQL with sp_executesql and writing a 'ASC' or 'DESC' literal depending on the parameter.
That code is going to get very unmanageable very quickly as you'll need to double nest your CASE WHEN's... one set for the Column to order by, and nested set for whethers it's ASC or DESC
Might be better to consider using Dynamic SQL here...
DECLARE #sql nvarchar(max)
SET #sql = '
Select
tbl_houses.*
from tbl_houses
where
postal in (select zipcode from crm_zipcodes where web_region_id = ' + #webRegionID + ') ORDER BY '
SET #sql = #sql + ' ' + #sortBy + ' ' + #sortDirection
EXEC (#sql)
You could do it with some dynamic SQL and calling it with an EXEC. Beware SQL injection though if the user has any control over the parameters.
CREATE PROCEDURE GetAllHouses
set #webRegionID = 2
set #sortBy = 'case_no'
set #sortDirection = 'ASC'
AS
BEGIN
DECLARE #dynamicSQL NVARCHAR(MAX)
SET #dynamicSQL =
'
SELECT
tbl_houses.*
FROM
tbl_houses
WHERE
postal
IN
(
SELECT
zipcode
FROM
crm_zipcodes
WHERE
web_region_id = ' + CONVERT(nvarchar(10), #webRegionID) + '
)
ORDER BY
' + #sortBy + ' ' + #sortDirection
EXEC(#dynamicSQL)
END
GO