Automatically add columns to SQL Server - sql

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 .

Related

Handling duplicates in BigQuery (Nested Table)

I think this is a very simple question but I would like some guidance: I didn't want to have to drop a table to send a new table with the deduplicated records, like using DELETE FROM based on the query below using BigQuery, is it possible? PS: This is a nested table!
SELECT
*
FROM (
SELECT
*,
ROW_NUMBER()
OVER (PARTITION BY id, date_register) row_number
FROM
dataset.table)
WHERE
row_number = 1
order by id, date_register
To de-duplicate in place, without re-creating the table - use MERGE:
MERGE `temp.many_random` t
USING (
SELECT DISTINCT *
FROM `temp.many_random`
)
ON FALSE
WHEN NOT MATCHED BY SOURCE THEN DELETE
WHEN NOT MATCHED BY TARGET THEN INSERT ROW
It's simpler than the current accepted answer, as it won't ask you to match the current partitioning or clustering - it will just respect it.
Update: please also check Felipe Hoffa's answer which is simpler, and learn more on this post: BigQuery Deduplication.
You need to exclude row_number from output and overwrite your table using CREATE OR REPLACE TABLE:
CREATE OR REPLACE TABLE your_table AS
PARTITION BY DATE(date_register)
SELECT
* EXCEPT(row_number)
FROM (
SELECT
*,
ROW_NUMBER()
OVER (PARTITION BY id, date_register) row_number
FROM your_table)
WHERE
row_number = 1
If you donĀ“t have a partition field defined at the source, I recommend that you create a new table with the partition field to make this query work so that you can automate the process.

SQL Eliminate Duplicates with NO ID

I have a table with the following Columns...
Node, Date_Time, Market, Price
I would like to delete all but 1 record for each Node, Date time.
SELECT Node, Date_Time, MAX(Price)
FROM Hourly_Data
Group BY Node, Date_Time
That gets the results I would like to see but cant figure out how to remove the other records.
Note - There is no ID for this table
Here are steps that are rather workaround than a simple one-command which will work in any relational database:
Create new table that looks just like the one you already have
Insert the data computed by your group-by query to newly created table
Drop the old table
Rename new table to the name the old one used to have
Just remember that locking takes place and you need to have some maintenance time to perform this action.
There are simpler ways to achieve this, but they are DBMS specific.
here is an easy sql-server method that creates a Row Number within a cte and deletes from it. I believe this method also works for most RDBMS that support window functions and Common Table Expressions.
;WITH cte AS (
SELECT
*
,RowNum = ROW_NUMBER() OVER (PARTITION BY Node, Date_Time ORDER BY Price DESC)
FROM
Hourly_Data
)
DELETE
FROM
cte
WHERE
RowNum > 1

Inserting numerous incremental values in a column

Got a table with 1200 rows. Added a new column which will contain incremental values -
Candidate1
Candidate2
Candidate3
.
.
.
Candidate1200
What is the best way to insert these values , non manual way. I am using SQL Server 2008
Assuming there's an IDENTITY column (I called it id for this example):
UPDATE YOUR_TABLE
SET new_column = (SELECT 'Candidate'+ CAST(ROW_NUMBER() OVER(ORDER BY yt.id) AS VARCHAR(4))
FROM YOUR_TABLE yt
WHERE yt.id = YOUR_TABLE.id)
You might be able to use ROW_NUMBER
http://msdn.microsoft.com/en-us/library/ms186734.aspx
Perhaps perform a query that gets the row number and use that query to perform an update on the source table where you concatenate the Row Number with 'Candidate'.

My tricky SQL Update query not working so well

I am trying to update a table in my database with another row from another table. I have two parameters one being the ID and another being the row number (as you can select which row you want from the GUI)
this part of the code works fine, this returns one column of a single row.
(SELECT txtPageContent
FROM (select *, Row_Number() OVER (ORDER BY ArchiveDate asc) as rowid
from ARC_Content Where ContentID = #ContentID) as test
Where rowid = #rowID)
its just when i try to add the update/set it won't work. I am probably missing something
UPDATE TBL_Content
Set TBL_Content.txtPageContent = (select txtPageContent
FROM (select *, Row_Number() OVER (ORDER BY ArchiveDate asc) as rowid
from ARC_Content Where ContentID = #ContentID) as test
Where rowid = #rowID)
Thanks for the help! (i have tried top 1 with no avail)
I see a few issues with your update. First, I don't see any joining or selection criteria for the table that you're updating. That means that every row in the table will be updated with this new value. Is that really what you want?
Second, the row number between what is on the GUI and what you get back in the database may not match. Even if you reproduce the query used to create your list in the GUI (which is dangerous anyway, since it involves keeping the update and the select code always in sync), it's possible that someone could insert or delete or update a row between the time that you fill your list box and send that row number to the server for the update. It's MUCH better to use PKs (probably IDs in your case) to determine which row to use for updating.
That said, I think that the following will work for you (untested):
;WITH cte AS (
SELECT
txtPageContent,
ROW_NUMBER() OVER (ORDER BY ArchiveDate ASC) AS rowid
FROM
ARC_Content
WHERE
ContentID = #ContentID)
UPDATE
TC
SET
txtPageContent = cte.txtPageContent
FROM
TBL_Content TC
INNER JOIN cte ON
rowid = #rowID

Incrementing value based on criteria in a single database query

I have a table which has a column labeled 'sortorder' which is used to allow customer to manually change the order of each item. The table also has a column labeled 'CategoryId'.
I was curious, if I was bulk importing a set of data in which I knew all data, including CategoryId, how I could specify the incrimenting value for 'SortOrder' inside the query, so that it went from 1 to X within each unique CategoryId.
Thanks everyone.
I'm not sure I understand your question but I think what you're asking is how to synthesize an appropriate SortOrder during an insert into the table. You should use ROW_NUMBER() with partitioning by CategoryId. Of course you will need to define a sorting criteria that gives the propert order of '1 to X':
INSERT INTO myTable (SortOrder, CategoryId, <other columns> ...)
SELECT ROW_NUMBER() OVER (PARTITION BY CategoryId ORDER BY mySortCriteria)
, CategoryId
, <other columns> ...
FROM SourceTable;
Sounds like you're needing to use the row_number function in your import.
INSERT MyTable(SortOrder, ...)
SELECT SortOrder = row_number() over (partition by CatgoryID order by SomeOtherField), ...
FROM MyTable
For anyone who might come along later who is still in SQL Server 2000, here is another way to accomplish the task.
Using a staging table of some sort to fix up the data from the bulk insert. Make sure it has a column called sortorder which is initally populated with a 1 and an identity based id column.
then you can update this with a self join, something like
update t
set sortorder = t1.sortorder +1
from test t
join Test t1 on t.id = t1.id+1
Then put the data into your prod table.