Custom autogenerated ID in sql server - sql-server

How can I create a custom auto-generated ID in this format:
yyyymmdd-xxxxx
where:
yyyymmdd is the present date and
xxxxx is an auto increment integer number starting from 0
and the next day xxxxx should be restarted to 0.
Thanks

Create one autonumeric ID column in your db
save the date/time of each insert row.
Then use a ROW_NUMBER() function
SELECT *,
dayField + '-' + CAST(rn AS VARCHAR(100))
FROM (
SELECT ID, dateTimeField,
-- truncate the time and convert to yyyymmdd
CONVERT(VARCHAR(10), cast(dateField As Date), 112) as dayField,
ROW_NUMBER() OVER (PARITION BY cast(dateField As Date)
ORDER BY dateTimeField) as rn
-- or just ORDER BY ID
) T
Now if you want save this on the db, you probably will need a trigger.

You might consider including an Identity column and a datetime column that will be set on insert and than add a calculated column to put the two together.

Related

SQL Server - Add results of a SELECT query to an existing table

I currently have a table in SQL Server called masterTable. What I'd like to do is to add a new column to this table called report_Date.
I would like to store the results of a SELECT query in the report_Date column. The query works fine (it converts a nvarchar into a desired date format). What I can't do is append the results to the column.
My query:
SELECT
CONVERT(varchar(10), CAST(FileName AS date), 103) AS FileName
FROM dbo.masterTable
Any suggestions please?
If I understand your question correctly then
UPDATE dbo.masterTable SET
report_Date = CONVERT(varchar(10), CAST(FileName as date), 103)

SQl Server - Where clause uses maximum date in data

I'm struggling with something i thought would be easy.
I have a table that is updated via an append on most days and has a report date field that shows the date the rows were updated.
I want to join to this table but only pull back the records from the date the table was last updated
Most of the time I could get away just looking for yesterdays date as the table is updated most days
Where [reportdate] > DATEADD(DAY, -1, GETDATE())
But as its not always updated daily, I wanted to rule this issue out. Is there anyway of returning the max date?
I was trying to figure out max (date), but I can't figure out the grouping. I need to return all the fields. The below just seems to return the whole table
SELECT max ([ReportDate]) as reportdate
,[GUID]
,[Make]
,[Model]
,[MPxN]
,[PaymentMode]
,[Consent]
,[Category]
,[Fuel]
,[pkCommCompID]
FROM table
group by guid
,[Make]
,[Model]
,[MPxN]
,[PaymentMode]
,[Consent]
,[Category]
,[Fuel]
,[pkCommCompID]
I could get round it with a temp table that just has the max report date and then using this as the left part of a join
SELECT max ([ReportDate]) as reportdate
FROM [DOMCustomers].[dbo].[DCC_Device_Comms_Compiled]
But The SQL is triggered in Excel so temp tables are problematic (i think).
Is there anyway of returning the max date?
Like this:
SELECT *
FROM SomeTable
where ReportDate = (select max(ReportDate) from SomeTable)
Here is a conceptual example.
It will produce a latest row for each car make.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (ID INT IDENTITY PRIMARY KEY, make VARCHAR(20), ReportDate DATETIME);
INSERT INTO #tbl (make, ReportDate) VALUES
('Ford', '2020-12-31'),
('Ford', '2020-10-17'),
('Tesla', '2020-10-25'),
('Tesla', '2020-12-30');
-- DDL and sample data population, end
;WITH rs AS
(
SELECT *
, ROW_NUMBER() OVER (PARTITION BY make ORDER BY ReportDate DESC) AS seq
FROM #tbl
)
SELECT * FROM rs
WHERE seq = 1;
Seems like a DENSE_RANK and TOP would work (assuming ReportDate is a date):
SELECT TOP (1) WITH TIES
[ReportDate]
,[GUID]
,[Make]
,[Model]
,[MPxN]
,[PaymentMode]
,[Consent]
,[Category]
,[Fuel]
,[pkCommCompID]
FROM YourTable
ORDER BY DENSE_RANK() OVER (ORDER BY ReportDate DESC);
If ReportDate is a date and time value, and you want everything for the latest date (ignoring time), then replace ReportDate with CONVERT(date,ReportDate) in the ORDER BY.

SQL Server : convert datetime in place in table

Basically I inherited a rather large table which has a few columns with dates formatted as varchar(10) of '##.##.####' (day.month.year). I would like to convert these columns to Datetime columns for that specific date.
Is there anyway to convert these in place on SQL Server (through a single set of SQL queries), instead of SELECTing each record in some programming language, converting the date and then UPDATEing back as Datetime (perhaps to a different column)?
There is no need in ...=(select...) The action is simple and straightforward.
ALTER TABLE YourTable
ADD NewDateColumn DATETIME
update YourTable set NewDateColumn = convert(date, OldDateColumn, 104)
--Magic 104 is for dd.MM.yyyy date format
That's all.
How about this as an alternative to Jim's comment. First add new DATE column:
ALTER TABLE YourTable
ADD NewDateColumn DATETIME
Then to UPDATE (I suppose you would want to use the same standard you've been using):
UPDATE t
SET t.NewDateColumn = (SELECT CONVERT(DATE, OldDateColumn, 104)
FROM YourTable ta WHERE t.ID = ta.ID)
FROM YourTable t
For someone that might want to get it from the German standard to the U.S. standard:
UPDATE t
SET t.NewDateColumn = (SELECT CONVERT(DATETIME,
CONVERT(DATE, OldDateColumn, 104)
,101)
FROM YourTable ta WHERE t.ID = ta.ID)
FROM YourTable t
This is assuming you do have an ID column.

SQL Select for create daily log data from more than one date column frrom a single table

I have a table with more than one date column,
each date column hold a date or null value,
I want to write a SQL query which will display each column have date into a new row with a new additional column named LogDate that contain the same date of column.
Its difficult to explain, please referrer the attached image.
Just use UNION ALL to concatenate the three result sets:
SELECT [ReceivedDate] AS LogDate, * FROM MyTable WHERE [ReceivedDate] IS NOT NULL
UNION ALL
SELECT [Closing Date] AS LogDate, * FROM MyTable WHERE [Closing Date] IS NOT NULL
UNION ALL
SELECT [LPODate] AS LogDate, * FROM MyTable WHERE [LPODate] IS NOT NULL
To sort by LogDate simply add the following ORDER BY clause to the end of this query:
ORDER BY LogDate

how to set order by date columns in sql server

i have a table in DB and columns like
01-03-2013
01-04-2013
02-03-2013
i want show order by like
01-03-2013
02-03-2013
01-04-2013
Please help me.
Most probably your column is not stored as one of the date datatype this is being sorted as a string based on ASCII codes
You can cast your column for sorting.
SELECT * FROM tbl
ORDER BY CONVERT(datetime, userColumn, 106)
otherwise it's straight forward
SELECT * FROM tbl
ORDER BY userColumn
If your column contain invalid records as well, you can use default date for such records
SELECT * FROM tbl
ORDER BY CONVERT(datetime,
CASE ISDATE(userColumn)
WHEN 1 THEN userColumn
ELSE '01-01-1900'
END, 106)

Resources