I have an MSSQL table with no id column, mainly because I accidentally dropped it and so recreated the column. Is there a way in SQL of automatically adding values to it so I don't have to manually sit there putting an ID number?
Use a CTE for an initial repopulation:
with CTE as
(
select t1.*, row_number() over (order by AnyColumn) as RN
from MyTable t1
)
update CTE
set ID = RN
Solutions 1: Restore Latest Backup on test DB then updated Id's in New Column
Solutions 2: Update Id's From Other Relational table based on column mapping .
I want to insert sequential numbers into a single column.
The columns have been set to NULL
Is there a command I can now use to populate just that column with sequential numbers
Thanks
you can use row_number analytic function to generate sequence number, that can be used to update the values.
WITH cte
AS
( SELECT ROW_NUMBER() OVER ( ORDER BY (SELECT null)) as rn , column1
FROM table1
)
UPDATE cte
SET column1 = rn
Based on your comment:
that almost did it but it would be nice if we can get it to sequence
properly for instance like 0000001, 0000002,0000003 etc up to 7
characters
I think this is what you are trying to do:
SELECT RIGHT('0000000' + CONVERT(VARCHAR, ROW_NUMBER() OVER ( ORDER BY COLUMN_NAME)), 7) AS ROW_NUM
FROM TABLE_NAME
Update after comment:
Basically this is what I am trying to do. I will be running a query to
grab those 7 character ID from that ALTATH column that will be used as
Reference ID so the column should have those output or type in
it..hope that's clear...thanks
I would personally use an Identity column and format the output when selecting records like this:
SELECT RIGHT('0000000' + CONVERT(VARCHAR, ID_COLUMN), 7) AS ROW_NUM
FROM TABLE_NAME
If you use the analytical functions the ROW_NUM column will not be the same everytime. If you use Identity SQL Server will take care of assigning the numbers in sequence for you. That is the DBMS's job.
How can I set all values in OrderNumber column from 1 to n(when they are ordered by primary key) where n is entries count in table?
EDIT:
Let's assume we have 3 entries with ID's 4,7 and 15 ... I want to set their OrderValues 1,2 and 3.
I'm using SQL Server 2008.
;WITH x AS (SELECT ID, OrderValues,
rn = ROW_NUMBER() OVER (ORDER BY ID)
FROM dbo.tablename
)
UPDATE x SET OrderValues = rn;
However, why on earth do you want to do this, when you can derive this information using the ROW_NUMBER() function at query time? Storing the values means that they are guaranteed to be out of date and out of sync the moment you insert/update/delete a single row in the table. So unless you plan to run this update after every DML operation (e.g. using a trigger), which isn't very logical to me, you're likely much better off getting these row_number values when you run the query vs. storing them in the table.
I have a query that allows me to get records from a database table by giving it a minimum and maximum limit.
It goes like this:
SELECT T1.CDUSUARIO, T1.DSALIAS, T1.DSNOMBRE_EMPRESA, T1.DSCARGO, T1.DSDIRECCION_CORREO, T1.CDUSUARIO_ADMINISTRADOR, T1.FEMODIFICACION
FROM (SELECT *,
ROW_NUMBER() OVER (ORDER BY CDUSUARIO) as row FROM TBL_USUARIOS ) as T1
WHERE row > #limiteInf
and row <= #limiteSup
ORDER BY DSALIAS ASC;
Now, it works like heaven on SQL Server 2005 and SQL Server 2008 but tried to run it on an SQL Server 2000 database and says:
ROW_NUMBER it's an unknown function name or something like that.
What can I do??
There is a COUNT(*) with SELF JOIN solution here that will scale badly
You can load a temp table with an IDENTITY column and read back but it's not guaranteed to work (can't find article on it, was told at an MS Seminar years ago)
Neither solution will support PARTITION BY
I've not mentioned loop or CURSOR based solutions which are probably worse
Edit 20 May 20011
Example demo of why IDENTITY won't work: Do Inserted Records Always Receive Contiguous Identity Values
I know this thread is bit old, but for anyone else looking for same solution, I think it will be useful to know that there is a good solution for this problem.
Please see the original link here
For those who do not want to click on the link, I have copied and pasted the code below. Again, credit goes to original publisher
Here is the below SQL for SQL Server 2000 to select the latest version of a record grouping by a single column.
SELECT *
FROM (
SELECT *, (
SELECT COUNT(*)
FROM MyTable AS counter
WHERE counter.PartitionByColumn = MyTable.PartitionByColumn
AND counter.OrderByColumn >= MyTable.OrderByColumn
) AS rowNumber
FROM MyTable
) AS r1
WHERE r1.rowNumber = 1
Same code in SQL Server 2005 would look like this:
SELECT * FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY PartitionByColumn
ORDER BY OrderByColumn DESC) AS rowNumber FROM MyTable) AS rw1
WHERE rw1.rowNumber = 1
Use another function or upgrade your database. ROW_NUMBER did not exist back in the 2000 version of the database. Point. Nothing you can do about it.
This is my solution to the problem:
declare #i int
declare #t table (row int, stuff varchar(99))
insert into #t
select 0,stuff from mytable -- <= your query
set #i=0
update #t set row=#i, #i=#i+1
select * from #t
Explanation:
create a memory table
insert data (your query) with the row number as 0
update the row number field with an int variable which is incremented in the same update for the next record (actually the variable is incremented first and then updated, so it will start from 1)
"select" the result from the memory table.
You may ask, why don't i use the variable in the select statement? It would be simpler but it's not allowed, only if there is no result. It's ok to do it in an update.
What is the most efficient way to read the last row with SQL Server?
The table is indexed on a unique key -- the "bottom" key values represent the last row.
If you're using MS SQL, you can try:
SELECT TOP 1 * FROM table_Name ORDER BY unique_column DESC
select whatever,columns,you,want from mytable
where mykey=(select max(mykey) from mytable);
You'll need some sort of uniquely identifying column in your table, like an auto-filling primary key or a datetime column (preferably the primary key). Then you can do this:
SELECT * FROM table_name ORDER BY unique_column DESC LIMIT 1
The ORDER BY column tells it to rearange the results according to that column's data, and the DESC tells it to reverse the results (thus putting the last one first). After that, the LIMIT 1 tells it to only pass back one row.
If some of your id are in order, i am assuming there will be some order in your db
SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE)
I think below query will work for SQL Server with maximum performance without any sortable column
SELECT * FROM table
WHERE ID not in (SELECT TOP (SELECT COUNT(1)-1
FROM table)
ID
FROM table)
Hope you have understood it... :)
I tried using last in sql query in SQl server 2008 but it gives this err:
" 'last' is not a recognized built-in function name."
So I ended up using :
select max(WorkflowStateStatusId) from WorkflowStateStatus
to get the Id of the last row.
One could also use
Declare #i int
set #i=1
select WorkflowStateStatusId from Workflow.WorkflowStateStatus
where WorkflowStateStatusId not in (select top (
(select count(*) from Workflow.WorkflowStateStatus) - #i ) WorkflowStateStatusId from .WorkflowStateStatus)
You can use last_value: SELECT LAST_VALUE(column) OVER (PARTITION BY column ORDER BY column)...
I test it at one of my databases and it worked as expected.
You can also check de documentation here: https://msdn.microsoft.com/en-us/library/hh231517.aspx
OFFSET and FETCH NEXT are a feature of SQL Server 2012 to achieve SQL paging while displaying results.
The OFFSET argument is used to decide the starting row to return rows from a result and FETCH argument is used to return a set of number of rows.
SELECT *
FROM table_name
ORDER BY unique_column desc
OFFSET 0 Row
FETCH NEXT 1 ROW ONLY
SELECT TOP 1 id from comission_fees ORDER BY id DESC
In order to retrieve the last row of a table for MS SQL database 2005, You can use the following query:
select top 1 column_name from table_name order by column_name desc;
Note: To get the first row of the table for MS SQL database 2005, You can use the following query:
select top 1 column_name from table_name;
If you don't have any ordered column, you can use the physical id of each lines:
SELECT top 1 sys.fn_PhysLocFormatter(%%physloc%%) AS [File:Page:Slot],
T.*
FROM MyTable As T
order by sys.fn_PhysLocFormatter(%%physloc%%) DESC
SELECT * from Employees where [Employee ID] = ALL (SELECT MAX([Employee ID]) from Employees)
This is how you get the last record and update a field in Access DB.
UPDATE compalints SET tkt = addzone &'-'& customer_code &'-'& sn where sn in (select max(sn) from compalints )
If you have a Replicated table, you can have an Identity=1000 in localDatabase and Identity=2000 in the clientDatabase, so if you catch the last ID you may find always the last from client, not the last from the current connected database.
So the best method which returns the last connected database is:
SELECT IDENT_CURRENT('tablename')
Well I'm not getting the "last value" in a table, I'm getting the Last value per financial instrument. It's not the same but I guess it is relevant for some that are looking to look up on "how it is done now". I also used RowNumber() and CTE's and before that to simply take 1 and order by [column] desc. however we nolonger need to...
I am using SQL server 2017, we are recording all ticks on all exchanges globally, we have ~12 billion ticks a day, we store each Bid, ask, and trade including the volumes and the attributes of a tick (bid, ask, trade) of any of the given exchanges.
We have 253 types of ticks data for any given contract (mostly statistics) in that table, the last traded price is tick type=4 so, when we need to get the "last" of Price we use :
select distinct T.contractId,
LAST_VALUE(t.Price)over(partition by t.ContractId order by created ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
from [dbo].[Tick] as T
where T.TickType=4
You can see the execution plan on my dev system it executes quite efficient, executes in 4 sec while the exchange import ETL is pumping data into the table, there will be some locking slowing me down... that's just how live systems work.
It is very simple
select top 10 * from TableName order by 1 desc
SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE)
I am pretty sure that it is:
SELECT last(column_name) FROM table
Becaause I use something similar:
SELECT last(id) FROM Status