I have a column in the database table i.e. transaction Id. Its data type is var char(50). Now I want to save a row by combining the current date with a sequential number generated.
For Example 10/9/2016 is the date so first transaction is saved like 10920161 and the next one like 10920162 and so on. The sequential number is reset to 1 after every day.
How can I do this?
In SQL Server, it can be as simple as:
transactionId =
CONCAT(DATEPART(MONTH, GETDATE()),
DATEPART(DAY, GETDATE()),
DATEPART(YEAR, GETDATE()),
(SELECT COUNT(1)
FROM tableName
WHERE CONVERT(DATE, dateColumn) = CONVERT(DATE, getdate())) + 1)
Get the Number of transactions for that date, and add one to it. Concat that with a formatted string of Today's Date.
If you already have 3 records for today's date, the result would be:
100920164
Running SQL-Fiddle
Edit: EF suggested snippet:
string dateStr = DateTime.Today.ToString("Mdyyyy");
DateTime todayMidnight = DateTime.Today;
DateTime tomorrowMidnight = DateTime.Today.AddDays(1);
obj.transactionId = dateStr +
context.tableName.Count(x=> x.dateColumn >= todayMidnight
&& x.dateColumn < tomorrowMidnight) + 1;
Related
When I define a "from" and "to" date to be the same value, the query is not returning any rows. When I select an extra day for the "to" date, then rows are returned.
string FrmDt = frmtx.Text.Trim();// 9/1/2015
string ToDt = totx.Text.Trim();//9/1/2015
select
rn.*,
(select count(reue) as RequtNo
from tblests
left join aspne u on r.custorid = u.userid
left join aspnethip a on u.Used=a.UserId
where
u.refere = rn.refid
and r.Compy = 'bbb'
and create >= '9/1/2015'
and create <= '9/1/2015') as refcount
from
tbl_reference rn
Datatype: [Createte] [datime] NOT NULL
How to convert 9/1/2015 12:00:00 AM to 9/1/2015 11:59:59 PM ?
You can simply use it like this:
createdate >= '9/1/2015 00:00:00'and createdate <= '9/1/2015 23:59:59'
or else you can switch to the next day and remove the = from <=
createdate >= '9/1/2015'and createdate < '9/2/2015'
To add time to your date you can try like this:
DateTime frmDt = new DateTime(2015, 09, 01); //time is 00:00:00 by default
DateTime toDt = new DateTime(2015, 09, 01);
TimeSpan toDtTime = TimeSpan.Parse("23:59:59");
DateTime toDtFinal = toDt.Add(ToDtTime);
Convert(date,StartTime) >= '2022-09-1' and Convert(date,EndTime) <= '2022-12-02'
It woked for me when I converted it to date from datetime.
Since your createdate field is a datetime and you define your date stating the date only, the time defaults to 00:00:01. You have three options to deal with that:
Set the range to 9/1/2015 - 9/2/2015, which would select whole 24
hours of 9/1/2015
Set the time explicitly to like 00:00:01 and 23:59:59 respectively like 'YYYY-MM-DD HH:MM:SS' (see https://dev.mysql.com/doc/refman/5.7/en/datetime.html for examples).
Do not define a range at all. Simply search for entries from a specific day like this:
...WHERE DATE(createdate) = '2015-09-01' ...
BTW: in MySQL you define dates as YYYY-MM-DD, so your '9/1/2015' should be '2015-09-01' in fact.
You can also use this way:
declare #tempDate datetime = '2015-09-01'
declare #endDate datetime = DATEADD(SECOND, -1, DATEADD(DAY, 1, #tempDate))
Here #tempDate os your current date. Now how #endDate is calculated, just add 1 day to #tempDate, then subtract 1 second from that, so you will get the today's date with max time. Now you can simply write query to get date between these two dates.
This works fine. Replace the hard coded date to the date column
string FrmDt = frmtx.Text.Trim();// 9/1/2015
string ToDt = totx.Text.Trim();//9/1/2015
select
rn.*,
(select count(reue) as RequtNo
from tblests
left join aspne u on r.custorid = u.userid
left join aspnethip a on u.Used=a.UserId
where
u.refere = rn.refid
and r.Compy = 'bbb'
AND (YEAR('9/1/2015')=2015 AND MONTH('9/1/2015')= 9 AND DAY('9/1/2015')=1)
--and create >= '9/1/2015'
--and create <= '9/1/2015') as refcount
from
tbl_reference rn
If you dont want to change the query like me, I added this in C# in code behind,
DateTime from =Convert.ToDateTime(_dataRange[0]);
DateTime to =Convert.ToDateTime(_dataRange[1]);
if (from == to)
{
to = to.AddHours(23.99); //this gives me 11:59PM in same date
}
I want to select the row of a database when the month of a date is accurate. for the year I did it:
select * from table where YEAR(date)='2015' it works well for the years
for the months I made :
select * from table where Month(date)='01'// I have the date format dd/mm/yyyy
thanks
From MONTH FUNCTION;
The Microsoft Access Month function returns the month (a number from 1
to 12) given a date value.
You should check it with an integer, not a string like;
select * from table where Month(date) = 1
Try this
select * from table where Month(date)='01' and YEAR(date)='2015'
I'm using asp.net MVC in my project. My database table includes some records. The table has datetime column for records. I want to get records of last week adding. So the LastlyRecords is:
DateTime.Now = 04.04.2015
LastWeekDateTime = 28.04.2015
LastWeekDateTime < LastlyRecords < DateTime.Now
Have a method that accepts a "Start Date" and "End Date" as parameters.
Call it with a start/end date like:
GetRecords(DateTime.Now.AddWeeks(-1), DateTime.Now);
For there, you can have a stored procedure fetch records between that date range (or do something similar for Entity Framework or whatever you're using).
You can do something similar in T-SQL via GETDATE() and DATEADD(), but it's arguably better to do the range calculation in the calling code (because it's more a business logic thing than a data access thing).
you have to write logic on your query or you can modify below as per your datetime range.
var lastweek = DateTime.Now.AddDays(7);
var records = d in db.Persons
where DateTime.Compare(lastweek, d.DateRecordColumn)
and DateTime.Compare(d.DateRecordColumn, DateTime.Now)
select d;
hope this help to resolve your query!!!
string dateTime = "01 April 2015 Wednesday 16:23";
DateTime time1 = Convert.ToDateTime(dateTime);
if (DateTime.Compare(DateTime.Now, time1) == 1 && // DateTime.Now > time1
DateTime.Compare(time1, DateTime.Today.AddDays((int)-7)) == 1 // time1 >= DateTime.Now-7days
)
{
#("True.")
}
else
{
#("False.")
}
The result is true, so it is in last week.
I am using SQL Server 2005, I am getting date from user in the format dd-MM-yyyy and limit of up to 5 days so user can see result upto +-5 days.
I tried a lot but unable to :
Convert dd-MM-yyyy into yyyy-MM-dd
Add days to dd-MM-yyyy in a SQL query
My SQL query is:
SELECT
(convert(varchar(10), OrderDate, 105)) AS OrderDate
FROM
[Products] p
WHERE
((convert(varchar(10), OrderDate, 105)) BETWEEN
(DATEADD(dd, -3, '22-01-2014'))
AND
(DATEADD(dd, 3, '22-01-2014'))
)
In above query, suppose user enters 22-01-2014 as date and 3 as flexibleDays (so user can see result from 19-01-2014 to 25-01-2014).
How can I add days in format dd-MM-yyyy in above SQL query?
I would recommend NOT use overuse the date conversion to and from strings! If you convert a DATE or DATETIME to a string - of course you cannot add days to it - it's a string now after all!
So if you already have a DATE or DATETIME column - use it and leave it's datatype alone!
Try code something like this:
-- define inputs from user - a date in string format, and a number of days
DECLARE #UserEntered VARCHAR(20) = '22-01-2014'
DECLARE #FlexiDays INT = 3
-- declare some helper variables - user input as DATE, from and to dates
DECLARE #UserEnteredDate DATE
DECLARE #FromDate DATE
DECLARE #ToDate DATE
-- determine the DATE the user entered, and the resulting "From" and "To" dates (as DATE)
SELECT #UserEnteredDate = CONVERT(DATE, #UserEntered, 105)
SET #FromDate = DATEADD(DAY, -1 * #FlexiDays, #UserEnteredDate)
SET #ToDate = DATEADD(DAY, #FlexiDays, #UserEnteredDate)
-- do your query without any messy conversions!
SELECT
OrderDate
FROM
[Products] p
WHERE
OrderDate BETWEEN #FromDate AND #ToDate
Try this function
CREATE FUNCTION SUBTRACT_DAYS( #date AS DATETIME, #days AS INT )
RETURNS DATETIME
BEGIN
RETURN DATEADD(dd, -#days, #date);
END
CREATE FUNCTION ADD_DAYS(#date AS DATETIME, #days AS INT )
RETURNS DATETIME
BEGIN
RETURN DATEADD(dd, +#days, #date);
END
SELECT dbo.SUBTRACT_DAYS('2014-01-22', 3),dbo.ADD_DAYS('2014-01-22', 3)
OP
Start End
2014-01-19 00:00:00.000 2014-01-25 00:00:00.000
Try this:
DECLARE #UserEntered VARCHAR(20) = '22-01-2014'
DECLARE #FlexiDays INT = 3
DECLARE #UserEnteredDate DATE
DECLARE #FromDate DATE
DECLARE #ToDate DATE
dates (as DATE)
SELECT #UserEnteredDate = CONVERT(DATE, #UserEntered, 105)
SET #FromDate = DATEADD(DAY, -1 * #FlexiDays, #UserEnteredDate)
SET #ToDate = DATEADD(DAY, #FlexiDays, #UserEnteredDate)
So I'm at the end of a long programming binge and I have one logical hurdle left to get over. My application presents KPIs for quote requests. The business leads have asked for these KPIs to be broken down by week, and I imagine when that is complete the request will come for a breakdown by month. I've figured this out in my SQL queries:
SELECT qpid FROM cpkpis WHERE DATEPART(ww, qpvalidfrom)=13 GROUP BY qpid;
Which will give my a list of qpids to compute a total from and provide actual primary keys for drill down.
What I can't get my head around is how to get an enumeration of weeks of the year form my C# code. I've looked the GregorianCalandar Class and specifically the GetWeekOfYear Method but I'm having trouble coming up with an enumeration of those values.
My question then is this: given a date range [lets say 2013-01-14 through 2013-04-10] how would I get an enumeration of the weeks of the year as ints between the start date and end date?
To help with with this task and the other requirements you're anticipating, you need a date table. IMHO the hardest thing to do in a database is to query data that isn't there.
You can query the date table:
Select Distinct DatePart(ww, dateField) as WeekNo
from DateTable
where dateField between '2013-01-14' and '2013-04-10';
From C#, an iterator is probably the simplest option:
public static IEnumerable<int> WeekNumbersBetween(
DateTime startDate,
DateTime endDate,
Calendar calendar = null,
CalendarWeekRule weekRule = CalendarWeekRule.FirstDay,
DayOfWeek firstDayOfWeek = DayOfWeek.Sunday)
{
if (calendar == null)
{
calendar = new GregorianCalendar();
}
DateTime week = startDate;
while (week <= endDate)
{
yield return calendar.GetWeekOfYear(week, weekRule, firstDayOfWeek);
week = week.AddDays(7);
}
}
The default values for the weekRule and firstDayOfWeek parameters should match the default settings in SQL. If your settings are different, you'll need to specify the correct values.
In T-SQL you could use something like:
DECLARE #StartDate DATE = '2013-01-14';
DECLARE #EndDate DATE = '2013-04-10';
WITH weekcte AS
(SELECT DATEADD(dd, -1, DATEADD(wk, DATEDIFF(wk, 0, #StartDate), 0)) AS DateValue
UNION ALL
SELECT DATEADD(wk, 1, DateValue)
FROM weekcte
WHERE DATEADD(wk, 1, DateValue) <= #EndDate )
SELECT DATEPART(ww, w.DateValue) AS 'Week No'
FROM weekcte AS w;