Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm new in TSQL.
I need to write a stored procedure which returns filtered records.
So the user has two dates to enter. He may enter only one date, or two, or both, or any.
In stored proc I have two params #From, #To - date type.
I need to search records.
If user didn't enter dates - I don't care about dates in the select query.
If the user entered 2 dates - I need to search with them inclusively.
If the user entered #From date - I need to search up to today inclusively.
If the user entered #To date - I need to search dates less than #To.
Thanks for your help.
SELECT ColumnList
FROM MyTable
WHERE
(#FromDate IS NULL OR FromDateColumn >= #FromDate)
AND (#ToDate IS NULL OR ToDateColumn <= #ToDate )
(But be aware that this can suffer from the effects of an unsuitable cached query plan due to parameter sniffing, especially if there is a large number of parameter conditions in the WHERE clause)
SELECT
Columns
FROM
Table
WHERE
DateColumn BETWEEN (CASE WHEN #FromDate IS NULL THEN DateColumn ELSE #FromDate END)
AND (CASE WHEN #ToDate IS NULL THEN DateColumn ELSE #ToDate END)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 21 hours ago.
This post was edited and submitted for review 10 hours ago.
Improve this question
dear gurus, SQL.
Please advise how to do the following:
You need to take a date from one column and join it with the time of another column,
and then add one day to the received date.
I wrote such a query, but on some data it gives a conversion error.
Please tell me a more optimal query so that it always works when combining the date and time format into datetime.
Thank you.
create table dt (date1 datetime, date2 datetime)
insert into dt values('19000101 17:17:00.000','19070101 17:51:00.000')
insert into dt values('19000101 18:20:00.000','19080101 18:21:00.000')
insert into dt values('20000101 06:00:00.000','20100101 06:40:00.000')
select
dateadd(dd,1,convert(datetime,convert(date,date1))+ convert(datetime,convert(time, date2)))
from dt
Here is an example where such an error could occur:
CREATE TABLE Example (
Duration TIME,
AdditionalDelay SMALLINT
)
INSERT INTO dbo.Example (Duration, AdditionalDelay)
VALUES ('00:01:02',3)
SELECT Duration+AdditionalDelay FROM dbo.Example
To fix this, you need to identify the proper unit of measure for AdditionalDelay and use DATEADD instead of +. For example:
SELECT DATEADD(MINUTE,AdditionalDelay,Duration) FROM dbo.Example
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I want to get 29-01-2021 in column in MYTABLE.
It will works if I:
insert into MYTABLE (column) -- datatype is date
select
Column -- datatype is datetime for example 29-01-2021 15:07:56.000
from OTHERTABLE
This will truncate the time portion, leaving you with a date value:
insert into MYTABLE (column) -- datatype is date
select
cast(Column as date)
from OTHERTABLE
so you want to put a datetime value into a date column, this can be done but you will loose the time portion off course
insert into MYTABLE (column) -- datatype is date
select
convert(date, Column) -- datatype is datetime for example 29-01-2021 15:07:56.000
from OTHERTABLE
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am inserting production orders into a SQL Server database with a stored procedure called via Microsoft PowerApps. Currently, the build date column is just using today's date as the build date. Attached below is a sample of records:
As you can see, all 10 of these orders have today's date as the set build date. However, I'd like to dynamically set this build date based upon the necessary output for the day. This will most likely be passed a variable to the stored procedure. For example - if the build output was 5 per day, rows 1-5 would have a build date of '02/17/2020' while the next 5 would have have a build date of '02/18/2020'.
This is simple enough since the number of orders is divisible by the build output. However, let's say the build output is 3 instead of 5. The first three orders would be '02/17/2020', the next three would be '02/18/2020', and the next three would be '02/19/2020'. This would leave one order to be set to '02/20/2020'. Then if I added more orders, it would stack upon each date filling each up to 3. Is there a way to do this via a stored procedure?
You might need to do some adjustments but based on my understanding, this will do the trick ([Date] is the date column in your sample table above):
CREATE PROC yourProcName #pNUM AS INT = 1 --PARAMETER
AS
(
DECLARE #pDate DATE;
SET #pDate = COALESCE((SELECT TOP 1 CONVERT(DATE, MAX([Date])), GETDATE()) FROM yourDestTable); --SETTING THE DATE AS MAX DATE ALREADY EXISTS IN THE TABLE. IF NOTHING IS THERE, WE'LL USE TODAY
DECLARE #pLead INT = COALESCE((SELECT TOP 1 COUNT(*) FROM yourDestTable WHERE [Date] = #pDate), 0);--SEE HOW MANY RECORDS IN THE DATABASE EXIST WITH THE DATE WE DEFINED
WITH cte
AS
(
SELECT *,
FLOOR((
ROW_NUMBER() OVER(ORDER BY #pDate) -
0.001)/#pNUM) AS RN -- SEPARATING RECORDS USING ROW_NUMBER DIVIDED BY DEFINED NUMBER OF PRODS PER DAY. USING FLOOR AND MINUS A SMALL AMOUNT TO ROUND IT RIGHT
FROM yourSourceTable
)
INSERT INTO yourDestTable
SELECT
C.*,
DATEADD(DAY, LEAD(C.RN, #pLead), #pDate) AS [Date] --PUSHING THE NUMBER BASED ON ROWS ALREADY EXISTED WITH THE MAX_DATE
INTO yourDestTable
FROM cte AS C
)
You might want to use MOD in CTE based on your usecase. But the idea should work. Then call it like this EXEC yourProcName <number of transactionsday>
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am creating a new SQL table which will have a date column, which will contain only Month and Year (eg: November 2014). My concern is that I will need to match this column in a query to do a JOIN. A relevant extract of that query is shown below:
(
SELECT
ReservationStayID,
datename(m,StayDate) + ' ' + cast(datepart(yyyy,StayDate) as varchar) as [MTH],
count(*) AS [Nights Spent],
avg(RateAmount) as [Rate],
min(CreatedOn) as CreatedOn,
min(StayDate) as [DateOfArrival],
max(StayDate) as [DateOfDeparture]
FROM ReservationStayDate
GROUP BY ReservationStayID, datename(m,StayDate) + ' ' + cast(datepart(yyyy,StayDate) as varchar)
) x ON x.ReservationStayID = b.ReservationStayID
The date column of my new table will be matched with the output from line 3 of the query above (that is, datename(m,StayDate.....as [MTH])
I just want to get it right in my new table so that I don't mess up things later when doing JOINS,etc.
I've read that I can use smalldate, or split the Month and Year as Varchar in 2 columns. So, what would you recommend?
I recommend you to use one datetime column
if you are sure that you will never ever use the whole date you should go with two separate fields for month and year but you do must have those values split both sides of the join otherwise there will be no advantage going this path: month name will be a varchar/nvarchar column but year should be an integer as it will always be a number.
one of the advantages of two separate columns is that you don't have to make the math at every join so you must have these values separate both sides of the join.
what i mean is that you have to modify the structure of table ReservationStayDate also, adding month and year as sparate values; the easiest solution is to create two calculated columns.
if you can use persisted calculated columns you could also have indexes on these columns and that will likely improve performances when joining & searching.
THE advantage i see: if you need (and use only) the information 'month' and 'year' it is cumbersome and costly to translate a 'date' information wherever you need 'month' and 'year' in the whole application. you can make classes, helper methods and so on but if you store the 'clean' information in the database it is easier to use and maintain it at all levels.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
suppose i have two table and both tables consist of one date column eg
OUTTime
12:05:40
12:08:30
12:20:40
and other table consist of
INTime
12:10:35
12:12:23
12:16:40
12:30:11
Now i want rows with Minimum time difference between two tables like 12:08:30 and 12:10:35 gives me OUT and IN. Similarly 12:20:40 and 12:30:11 gives me another row here by eliminating OUTTime 12:05:40 and eliminating 12:12:35 and 12:16:40 from INTime which gives me proper OUtTime and InTime
Any suggestion how to loop to get this data?
If you want to get a matching InTimes and OutTimes and only get the closest, try this:
Set Up
CREATE TABLE #OUTTime
(
[Time] Time
)
INSERT INTO #OUTTime
VALUES
('12:05:40'),
('12:08:30'),
('12:20:40')
CREATE TABLE #InTime
(
[Time] Time
)
INSERT INTO #InTime
VALUES
('12:10:35'),
('12:12:23'),
('12:16:40'),
('12:30:11')
Now the query:
;WITH CTE
As
(
SELECT O.Time AS outTime, (SELECT MIN([Time]) FROM #InTime I WHERE I.[time] > O.[Time]) AS InTime
FROM #OUTTime O
)
SELECT MAX(OutTime) As OutTime, InTime
FROM CTE
GROUP BY InTime
Results
OutTime InTime
12:08:30.0000000 12:10:35.0000000
12:20:40.0000000 12:30:11.0000000
If you UNION the two tables ... something like
SELECT Time, 'IN'
FROM InTimesTable
UNION
SELECT Time, 'Out'
FROM OutTimesTable
Order by Time
You can dump it in excel, and manipulate it manually.
Or, you can fill out your question here, and get a better answer.