Issues with SQL Server LIKE clause - sql-server

I'm sure this is a VERY simple problem, but I've not been able to figure it out. Here's my query:
select column1 from table1 with(nolock)
where column1 like '2011-07-0[78]%'
order by column1 desc
As you can tell, I'm querying a row looking for timestamps that are from either today or yesterday.
A full timestamp within one of these rows looks like this:
2011-07-08 12:16:39.553
I've done similar things many times with no trouble, but the above query returns no results no matter what I try. (Yes, there are timestamps from today and yesterday in the column).
Have I made a syntax error? Am I crazy? Are there gnomes in my DB messing with my query? Please help! Thank you so much!

If the datatype for that field is datetime or smalldatetime then LIKE won't work as expected.
You could do a DATEPART function or BETWEEN, like:
WHERE DATEPART(Year, column1) = 2011
AND DATEPART(Month, column1) = 7
AND DATEPART(Day, column1) IN (7, 8)
or
WHERE column1 BETWEEN '2011-07-07' AND '2011-07-08'
Bear in mind BETWEEN is inclusive.

try this :
select column1 from table1 with(nolock)
where Cast(column1 as DateTime) between '2011-07-07' AND '2011-07-08'
order by column1 desc

Related

Sql server convert datetime to ''YYYY-MM-DD'T'HH:mm:ss.SSS'Z"

In SQL Server, I have a column start_date in Table1 (2 values shown below)
'2006-08-15 00:00:00.000',
'2010-07-13 18:53:59.000'
I want to convert these dates to format "yyyy-mm-dd'T'hh:mm:ss.SSS'Z'".
I have tried both of the following things:
Select Convert(varchar, start_date, 126) + 'Z' as required_date from Table1
Select Convert(varchar, start_date, 127) + 'Z' as required_date from Table1
I get these results:
'2006-08-15T00:00:00Z'
'2010-07-13 18:53:59Z'
Last 000 is getting trimmed out (that should not happen).
I want result like this:
'2006-08-15T00:00:00.000Z'
'2010-07-13 18:53:59.000Z'
How can I achieve this? Any help would be appreciated.
Thanks.
I'm new to sql but I assume that the removal of .000 is because of sql itself not showing milliseconds or whatever that is. Try adding '.000Z' where you add 'Z' and you should have it?
Should look like this
Select Convert(varchar,start_date,126)+'.000Z' as required_date from Table1
Select Convert(varchar,start_date,127)+'.000Z' as required_date from Table1
You can use below
Select Convert(varchar(25),start_date,121)+'Z' as required_date from Table1
Some good explanation here SQL Convert Date functions and formats
As of now I can see only one way to get the desired answer:
Select
CONVERT(varchar(20),start_date,126)+
substring(CONVERT(varchar(35),start_date,121),20,23)+'Z'
AS required_date from Table1
Please comment if any optimized way.

SQL Server equivalent of dense_Rank() and TO_DATE() of Postgres

I have the below query coming from the Postgres database. I want to convert the below query from Postgres to an Azure SQL Server version.
I know that TO_DATE can be written as convert(DATETIME,...) but I want to protect the date format too. Even after changing TO_DATE, there are still errors. Can someone help me with this?
SELECT b.*
FROM (
SELECT MAX(gs.ID),
dense_rank() over (order by gs.TIME_COLUMN DESC ) AS latest
FROM TEST_TABLE gs
WHERE TIME_COLUMN BETWEEN TO_DATE('%time_parameter%', 'YYYY-MM-DD HH24:MI:SS')
AND TO_DATE('%time_parameter2%', 'YYYY-MM-DD HH24:MI:SS')
GROUP BY gs.OTHER_ID, gs.TIME_COLUMN
) a
LEFT JOIN TEST_TABLE b ON max.latest = b.ID
The equivalent to ensuring YYYY-MM-DD isn't incorrectly interpreted as YYYY-DD-MM in some languages is to explicitly specify a style number during the convert:
WHERE TIME_COLUMN
BETWEEN CONVERT(datetime, '%time_parameter%', 21)
AND CONVERT(datetime, '%time_parameter2%', 21)
For a full list of styles, see Build a cheat sheet for SQL Server date and time formats.
As Larnu and Panagiotis commented, it would be much better if you use a language-neutral format, like yyyy-MM-ddThh:mm:ss.nnn, and/or datetime2 in place of datetime, which will prevent language settings from interfering with datetime parsing.
And as an aside, BETWEEN should generally be avoided for date range queries; see the first couple of links at Dating Responsibly.
This is the SQL Server version of the above query. Thanks for the discussions but this one and a bit of trying solved the issue.
SELECT b.*
FROM (
SELECT MAX(gs.ID) as max,
dense_rank() over (order by gs.TIME_COLUMN DESC ) AS latest
FROM TEST_TABLE gs
WHERE TIME_COLUMN BETWEEN CONVERT(DATETIME, '%time_parameter%')
AND CONVERT(DATETIME, '%time_parameter2%')
GROUP BY gs.OTHER_ID, gs.TIME_COLUMN
) a
LEFT JOIN TEST_TABLE b ON a.max = b.ID

Datediff last and previous dates SQL

I'm learning SQL, for an exercise I have to several things.
I'm making a query to compare the most recent orderdate with the orderdate before. I want to use a correlated subquery for this. I have already made it using a Cross Apply and Window functions.
At the moment I have this:
select
b1.klantnr,
DATEDIFF(D, (Select MAX(b1.Besteldatum)),
(Select MAX(b1.Besteldatum)
where besteldatum not in (Select MAX(b1.besteldatum)))) as verschil
from
bestelling b1
group by
b1.klantnr, b1.besteldatum
I only get null values in the datediff column. It should return this:
Results
I'm using SQL Server 2014 Management Studio.
Any help appreciated.
Here is one simple way:
select datediff(day, min(bs.Besteldatum), max(bs.Besteldatum)) as most_recent_diff
from (select top (2) bs.*
from bestelling bs
order by bs.Besteldatum
) bs;
This uses a subquery, but not a correlated subquery. Should have really good performance, if you have an index on bestselling(Besteldatum).
A correlated subquery way.
select top 1 bs.*,datediff(day,
(select max(bs1.Besteldatum)
from bestelling bs1
where bs1.Besteldatum<bs.Besteldatum),
bs.Besteldatum
) as diff
from bestelling bs
order by bs.Besteldatum desc
This gives only the difference between latest date and the date preceding it. If you need all records remove top 1 from the query.

Order By not working on datetime 101 format

Create table #temp
(
OrderDate datetime
)
insert into #temp values ('01/21/2015'),('01/20/2014'),('11/12/2013')
select distinct convert(varchar(10),orderdate,101) as OrderDate from #temp
order by convert(varchar(10),orderdate,101) asc
The above query gives me the result like below:
OrderDate
01/20/2014
01/21/2015
11/12/2013
But I want the result like below:
OrderDate
11/12/2013
01/20/2014
01/21/2015
The above is just a sample on which I am trying to do sorting on format 101. In my actual query I need to use distinct keyword and also the columns will come dynamically in the select statement by using parameter.
I can't use group by in my actual query.
Please help.
UPDATE
Referring to your comments the only way I've managed to get the UNIQUE results with only one column orderdate converted to VARCHAR 101 representation while still sorting it according to DATETIME sort order, was using a little workaround with GROUP BY clause:
SELECT
CONVERT(VARCHAR(10), A.OrderDate, 101) as orderdate
FROM
#temp AS A
GROUP BY
CONVERT(VARCHAR(10), A.OrderDate, 101)
ORDER BY
MAX(A.OrderDate) ASC
MAX(A.OrderDate) should always give you the exactly equal value to the value of every group, so it shouldn't be an improper way - I've put a working example with repeats under the following link on SQL Fiddle.
Still maybe the previous two-columned solution would happen to occur helpful:
select distinct
convert(varchar(10),orderdate,101) as OrderDateConverted,
orderdate
from
#temp
order by
orderdate asc
The above query sorts your query results according to DATETIME datatype whereas order by convert(varchar(10),orderdate,101) caused the alphanumeric sort order.
You can use subQuery as follows to solve the issue.
SELECT t.OrderDate FROM (
SELECT distinct Convert(VARCHAR(10), orderdate, 101) AS OrderDate
from #temp ) t
order by cast(t.OrderDate AS DATETIME) asc

Arithmetic overflow error converting expression in to data type datetime

Hoping someone can help. I've looked on the internet for a solution but none seem to resolve it.
I want to query a large table and only get the results back where a column equals today's date.
Here's the query:
select [Table1].[Field1]
from [Table1]
where [Table1].[Field1] = GetDate()
The date format is as follows:
20020630
I'm a beginner in SQL so any help would be really appreciated because I am growing fond of it.
Thank you!!! :)
To find the broken value:
select [Table1].[Field1]
from [Table1]
where ISDATE([Table1].[Field1]) = 0
GETDATE includes a time, so you need to remove this. This assumes SQL Server 2008+
select [Table1].[Field1]
from [Table1]
where [Table1].[Field1] = CAST(GetDate() AS date)

Resources