show records after current time - sql-server

Actually I want some records from my database. There is a field Time_From. I just want to show only those records which are after DateTime.Now().
But it is not showing, it shows records before and after DateTime.Now()
Select *
from mytable
where Vehicle_Booking_Date= #Vehicle_Booking_Date
AND Time_From > #Time_From order by Time_From"
The table definition (from the comment)
CREATE TABLE [dbo].[mtblVehicle_Booking]
(
[Sno] [int] IDENTITY(1,1) NOT NULL,
[Vehicle_Number] [nvarchar](100) NULL,
[Vehicle_Booking_Date] [datetime] NULL,
[Time_From] [datetime] NULL,
[Time_To] [datetime] NULL,
[Vehicle_Used_By] [varchar](100) NULL,
[Vehicle_Booked_By] [varchar](100) NULL,
[Cost_Code] [nvarchar](50) NULL,
[Budget_Line] [nvarchar](50) NULL,
[Purpose] [varchar](20) NULL,
[Destination] [nvarchar](500) NULL,
[Trip_Details] [nvarchar](500) NULL
)
ON [PRIMARY]

If you want to select all records whose Time_From is greater than current time and date is equal to specified date,
Select *
from mytable
where Vehicle_Booking_Date= #Vehicle_Booking_Date
AND Time_From > now() order by Time_From'

You have not mentioned what database you are using. But concept remains same. Just substract the other date time from current time. If it is greater than 0 it means that the given date time is greater than the current date time.
Sample SQL
Select *
from mytable
where Vehicle_Booking_Date= #Vehicle_Booking_Date
AND DATEDIFF(Time_From,SYSDATETIME()) > 0
Hope this helps.

Related

Finding recurring events that fall between two dates

I have been tasked with creating an events calendar for a website which will be backed by SQL Server. Using some of the information listed at: Calendar Recurring/Repeating Events - Best Storage Method I have created two tables in the database;
CREATE TABLE [Calendar].[Event](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Title] [nvarchar](100) NOT NULL,
[Details] [nvarchar](max) NOT NULL,
[EventType] [int] NOT NULL,
[Dismissable] [bit] NOT NULL DEFAULT ((1)),
[Created] [datetime2](7) NOT NULL DEFAULT (getdate()),
[CreatedBy] [uniqueidentifier] NOT NULL,
[LastEdited] [datetime2](7) NOT NULL DEFAULT (getdate()),
[EditedBy] [uniqueidentifier] NOT NULL
)
CREATE TABLE [Calendar].[EventSchedule](
[Id] [int] IDENTITY(1,1) NOT NULL,
[EventId] [int] NOT NULL,
[StartDate] [datetime2](7) NOT NULL,
[EndDate] [datetime2](7) NULL,
[IntervalDays] [int] NULL,
[IntervalWeeks] [int] NULL,
[IntervalMonths] [int] NULL,
[IntervalYears] [int] NULL,
[WeekDayNumber] [int] NULL,
[MonthWeekNumber] [int] NULL,
[YearMonthNumber] [int] NULL
)
I am now attempting to write a stored procedure to capture all events (singular and recurring) that fall between a date range, but cannot get my head around a catch all solution that doesn't involve generating temporary tables or cursors.
My current roadblock is the events that recur every n days. So far I have the following:
CREATE PROCEDURE Calendar.GetEventsForDateRange
#StartDateRange DATETIME2
#EndDateRange DATETIME2
AS
BEGIN
SELECT * --for brevity
FROM Calendar.EventSchedule
WHERE (StartDate <= #EndDateRange
AND DATEDIFF(DAY, StartDate, #EndDateRange) / IntervalDays >= 1)
OR (StartDate >= #StartDateRange AND StartDate <= #EndDateRange)
END
I have an event where StartDate = 2017-07-02 and IntervalDays = 7. If I pass a #StartDateRange = 2017-07-03 and #EndDateRange = 2017-07-09 the event is correctly returned. If I then change the #StartDateRange = 2017-07-13 and #EndDateRange = 2017-07-15 the event is still returned, where its next occurrence should be 2017-07-16.
How would I alter/amend my current stored procedure to return events that will only occur within a date range?
Any help on this would be greatly appreciated.

How can I find last row in multiple group by WITHOUT window functions over?

I have a query that returns a result fairly quickly:
SELECT [Date],[AccountCode],[ModelCode],[Generic],SUM([MTMusd]) AS 'MTMusd'
FROM [dbo].[MTM]
WHERE [AccountCode] = 'XXX'
AND [ModelCode] = '1'
GROUP BY [Date],[AccountCode],[ModelCode],[Generic]
ORDER BY [Date]
CREATE TABLE [dbo].[MTM](
[AccountCode] [nvarchar](50) NULL,
[ModelCode] [nvarchar](50) NULL,
[Date] [date] NULL,
[TIMESTAMP] [time](7) NOT NULL,
[Generic] [nvarchar](50) NULL,
[MTMUsd] [float] NOT NULL
) ON [PRIMARY]
However, I don't want SUM() I want LAST().
In the GROUP BY I have missed out [TIMESTAMP] which is the time of day. I want my query to return the record with the LAST TIMESTAMP for each GROUP { [Date],[AccountCode],[ModelCode],[Generic] }
How can I achieve this efficiently? I have approx 5 millions rows.
I tried ROW_NUMBER() OVER () based example I found, but processing took an order of minutes.

Get Sum amount against a distinct Value

I want to get sum amount ( Field name Amount) against all the distinct values of Description fields.
CREATE TABLE [dbo].[TransLine](
[TransID] [int] NULL,
[No] [int] NULL,
[Description] [varchar](50) NULL,
[Qty] [varchar](50) NULL,
[Rate] [decimal](18, 2) NULL,
[Amount] [decimal](18, 2) NULL,
[TDate] [datetime] NULL
) ON [PRIMARY]
GO
Kindly reply.
SELECT Description, SUM(Amount) AS [SUM]
FROM dbo.TransLine
GROUP BY Description
You really should at least make an attempt

Convert text to datetime, and select between two dates

I'm trying to get some values between two dates (the 100 last days). However my column is a text-field, formatted: 17.06.2013
SELECT
.....
WHERE Organizations.OrganizationID = '4360'
AND convert(datetime,convert(varchar(10),StatisticsDate),104) BETWEEN
convert(datetime,GETDATE()-100,104) AND convert(datetime,GETDATE(),104)
GROUP BY Groups.Name, GroupStatistics.StatisticsDate
Mssql error:
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
Can someone please tell me what I'm doing wrong?
Thank you! :-)
UPDATE:
[GroupStatisticsID] [int] IDENTITY(1,1) NOT NULL,
[GroupID] [int] NOT NULL,
[CreateUser] [nvarchar](max) NULL,
[StatisticsDate] [text] NULL,
[memberAttendants] [int] NOT NULL,
[Free] [int] NULL,
[FreeHours] [int] NULL,
[GroupName] [text] NULL,
[GroupNumber] [int] NULL,
[Ser] [text] NULL,
[SerNmbr] [int] NULL,
[SerName] [text] NULL
UPDATE2:
I tried SELECT GETDATE() which gave me: 2013-06-18 22:38:25:270
Does that mean I need to convert to this formatting to use BETWEEN?
The date comparision with between is not the problem in your case, since you casted already.
You will have to Group with Not text values:
GROUP BY Name, convert(datetime,convert(varchar(10),StatisticsDate),104)

TSQL Help (SQL Server 2005)

I have been playing around with a quite complex SQL Statement for a few days, and have gotten most of it working correctly.
I am having trouble with one last part, and was wondering if anyone could shed some light on the issue, as I have no idea why it isnt working:
INSERT INTO ExistingClientsAccounts_IMPORT
SELECT DISTINCT
cca.AccountID, cca.SKBranch, cca.SKAccount, cca.SKName, cca.SKBase,
cca.SyncStatus, cca.SKCCY, cca.ClientType, cca.GFCID, cca.GFPID, cca.SyncInput,
cca.SyncUpdate, cca.LastUpdatedBy, cca.Deleted, cca.Branch_Account, cca.AccountTypeID
FROM ClientsAccounts AS cca
INNER JOIN
(SELECT DISTINCT ClientAccount, SKAccount, SKDesc,
SKBase, SKBranch, ClientType, SKStatus, GFCID,
GFPID, Account_Open_Date, Account_Update
FROM ClientsAccounts_IMPORT) AS ccai
ON cca.Branch_Account = ccai.ClientAccount
Table definitions follow:
CREATE TABLE [dbo].[ExistingClientsAccounts_IMPORT](
[AccountID] [int] NOT NULL,
[SKBranch] [varchar](2) NOT NULL,
[SKAccount] [varchar](12) NOT NULL,
[SKName] [varchar](255) NULL,
[SKBase] [varchar](16) NULL,
[SyncStatus] [varchar](50) NULL,
[SKCCY] [varchar](5) NULL,
[ClientType] [varchar](50) NULL,
[GFCID] [varchar](10) NULL,
[GFPID] [varchar](10) NULL,
[SyncInput] [smalldatetime] NULL,
[SyncUpdate] [smalldatetime] NULL,
[LastUpdatedBy] [varchar](50) NOT NULL,
[Deleted] [tinyint] NOT NULL,
[Branch_Account] [varchar](16) NOT NULL,
[AccountTypeID] [int] NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[ClientsAccounts_IMPORT](
[NEWClientIndex] [bigint] NOT NULL,
[ClientGroup] [varchar](255) NOT NULL,
[ClientAccount] [varchar](255) NOT NULL,
[SKAccount] [varchar](255) NOT NULL,
[SKDesc] [varchar](255) NOT NULL,
[SKBase] [varchar](10) NULL,
[SKBranch] [varchar](2) NOT NULL,
[ClientType] [varchar](255) NOT NULL,
[SKStatus] [varchar](255) NOT NULL,
[GFCID] [varchar](255) NULL,
[GFPID] [varchar](255) NULL,
[Account_Open_Date] [smalldatetime] NULL,
[Account_Update] [smalldatetime] NULL,
[SKType] [varchar](255) NOT NULL
) ON [PRIMARY]
The error message I get is:
Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated.
The statement has been terminated.
The error is because you are trying to insert data into a column in ExistingClientsAccounts_IMPORT where the column size is smaller than the length of data attempting to be inserted into it.
e.g.
SKAccount column is VARCHAR(12) in the ExistingClientsAccounts_IMPORT table but is VARCHAR(255) in ClientsAccounts_IMPORT.
So if ClientsAccounts_IMPORT contains any rows where that field is longer than 12 characters, you will get that error as obv. e.g. 100 characters will not fit into a 12 character field.
You need to make sure all the columns in the table you are inserting into, are big enough - make sure each column definition matches the source table.
The third column of your SELECT column list means that ExistingClientsAccounts_IMPORT.SKAccount is populated from ClientsAccounts.SKAccount - however, the source is up to 255 characters, while the destination has a capacity of 12. If there's any data that wouldn't fit, you'll get this message.
I haven't gone through all the other columns.
You are trying to insert values which are greater than tha max length specified for a column. Use a profiler to check the data being passed to this query and verify the length of data against the permissible length for all columns.
There is a clear mismatch in the column lenghts of common columns of these two tables.
ClientsAccounts_IMPORT.SKBase is 10 whereas it is 16 in the other table.
Check the field definitions. You can see some are smaller than the original ones. Now run a query on the old data - you will find some of the larger fields were used, so the insert is not possible without losing data.
Example: SKAccount - from 255 length to 12.

Resources