Update existing schema using cursor - sql

I'm trying change existing schema to add new column.
Here is my case - http://sqlfiddle.com/#!3/06c58/1
Value of Order column is int, which should represent order of items on UI from 1 to COUNT(Id) if I'm grouping TemplateId.
I see 2 possible solutions - make Order calculated field or use Cursor to update it.
Which one is better? And if update using cursor win -
May I know how to have such update ?

One way I can think of it is this:
Start a transaction
Insert into columns apart from Order
Update the table to set Order values
Commit transaction if everything is OK, else rollback.
You won't need to directly deal with cursors to do this, and the operation will be atomic in a way, since it's wrapped in a transaction block.
The update itself can be done something like this:
;with ord as
(Select id, row_number() over (partition by templateid order by selectedfieldid) rn from yourtable)
Update dbo.titlefields
Set order = rn - 1 --ROW_NUMBER() starts at 1 but we want to start at 0
From dbo.titlefields t inner join
ord x on t.id = x.id
Please let me know if I have understood your requirement correctly, and I will update my answer if that is not so.

Related

SQL statement to perform incremental updates based upon conditon

I am trying to create a sql update statement that will look for a company name sort their accompanying materials alphabetically then update another field in the table in increments of ten after setting a seed value.
The pseudocode sql I envision is something like this
#orderincrement = 100
Update Materials
Set Order = #orderincrenment + 10
where CompanyName = 'ThisCompany'
order by materials
Current Table Example:
What I want it to look like after:
It has been a while since I have done sql scripting.
Please provide any suggestions.
Use window functions and an updatable CTE:
with toupdate as (
select m.*,
row_number() over (partition by comapnyname order by materials) as seqnum
from materials m
)
update toupdate
set order = #orderincrement + 10 * seqnum
where companyname = ?;
I am guessing a bit on the actual arithmetic that you want, but whether you want to start at 10 in increments of 100 or at 100 in increments of 10, most of the query is the same.

Incorporate a concatenation and count in a SQL update command?

I am looking for a way to update records so each entry adds 1 to the end of the string. In my case, I'm trying to update a field named FiberID. Each Record should have JCK0.R000.Ax, where x is equal to 1,2,3...,24.
Ideal result:
FiberID
JCK0.R000.A1
JCK0.R000.A2
JCK0.R000.A3
... and so on until it reaches A24.
Here is an example of the data.
This seems so useful that I'm sure it has been discussed here before, but for what ever reason I'm not seeing anything.
You could use an row_number and an updatable CTE:
with cte as (
select
fiber_id,
concat(
fiber_id,
'.A',
cast(row_number() over (partition by fiber_id order by id) as varchar(2))
) new_fiber_id
from mytable
)
update cte set fiber_id = new_fiber_id
This assumes that you have a column called id that can be used to order records having the same fiber_id.
Side note: it is unclear why you should have exactly 24 numbers per fiber_id, and you sample data does not describes that. This will assign increasing numbers to duplicate fiber_ids, regardless of how many there are.

Update Row ID using Order By [Help]

I can't seem to get this query to work I am pretty sure I have it correct but i keep coming up with errors. I am trying to create a update query to the rows and they way they are sorted by using a where clause to a specific section as well as a join.
Here is my query:
With cte As
(
SELECT Products.Products.PartNumber, Products.Prices.ProductID, Products.Prices.CODE, Products.Prices.Price
ROW_NUMBER() OVER (ORDER BY Price DESC) AS RN
FROM Test
JOIN Products.Prices
ON Products.Products.ID = Products.Prices.ProductID
where partnumber like 'l2%'
Order by Price Desc
)
UPDATE cte SET Number=RN
Thank you.
Instead of updating the row in the table, you could create a VIEW using your ORDER BY query and other queries could check the view instead of the row.
If you want to stick to just your table, you need to check and make sure the ROW ID being set isn't conflicting with any other row. For instance, if you ORDER BY and find row with ID=6 to be the first in the new query, you update it with ID=1. However, row 1 already has ID=1, and that conflicts with your new row ID (Previously row ID=6).

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.