Update column with ROW_NUMBER() value
I have a column that I would like to update with a ROW_NUMBER() value partitioned by a specific column.
CREATE TABLE ##tmp (id INT NULL,
value1 VARCHAR(10),
value2 VARCHAR(10))
INSERT INTO ##tmp (value1,
value2)
VALUES ('A', 'asdfasdf'),
('A', 'asdf'),
('A', 'VC'),
('B', 'aasdf'),
('C', 'sdfgs'),
('C', 'xdfbhsdty'),
('C', '23sdgfg'),
('C', '234')
-- update the ID column with the values below
SELECT ROW_NUMBER() OVER (PARTITION BY Value1 ORDER BY Value2),
Value1,
Value2
FROM ##tmp
I have 14 million records. Can someone explain the best way to do this? Does the ORDER BY destroy performance for this many records?
Thanks!
CREATE TABLE ##tmp (id INT NULL,
value1 VARCHAR(10),
value2 VARCHAR(10))
INSERT INTO ##tmp (value1,
value2)
VALUES ('A', 'asdfasdf'),
('A', 'asdf'),
('A', 'VC'),
('B', 'aasdf'),
('C', 'sdfgs'),
('C', 'xdfbhsdty'),
('C', '23sdgfg'),
('C', '234')
-- update the ID column with the values below
; with cte as (
SELECT ROW_NUMBER() OVER (PARTITION BY Value1 ORDER BY Value2) as RowNumber,
Value1,
Value2
FROM ##tmp
update cte
set Id = RowNumber;
Russel Loski, MCT, MCSE Data Platform/Business Intelligence. Twitter: @sqlmovers; blog: www.sqlmovers.com
Similar Messages
-
How to update a column with different values but all other row values r sam
Hi,
I have a table like this.
Col1 col2 col3 col4
10 20 30
10 20 30
10 20 30
i need to update col4 with different values coming from other table like this
Col1 col2 col3 col4
10 20 30 xxxx
10 20 30 yyyy
10 20 30 zzzz
how can i update the table. pls let me know how to use the where condition in the update stmt.
thanks,
jay
Edited by: user2558790 on Nov 20, 2009 12:26 PMwhat is the logic for this kind of update...????
Greetings,
Sim -
Sql query slowness due to rank and columns with null values:
Sql query slowness due to rank and columns with null values:
I have the following table in database with around 10 millions records:
Declaration:
create table PropertyOwners (
[Key] int not null primary key,
PropertyKey int not null,
BoughtDate DateTime,
OwnerKey int null,
GroupKey int null
go
[Key] is primary key and combination of PropertyKey, BoughtDate, OwnerKey and GroupKey is unique.
With the following index:
CREATE NONCLUSTERED INDEX [IX_PropertyOwners] ON [dbo].[PropertyOwners]
[PropertyKey] ASC,
[BoughtDate] DESC,
[OwnerKey] DESC,
[GroupKey] DESC
go
Description of the case:
For single BoughtDate one property can belong to multiple owners or single group, for single record there can either be OwnerKey or GroupKey but not both so one of them will be null for each record. I am trying to retrieve the data from the table using
following query for the OwnerKey. If there are same property rows for owners and group at the same time than the rows having OwnerKey with be preferred, that is why I am using "OwnerKey desc" in Rank function.
declare @ownerKey int = 40000
select PropertyKey, BoughtDate, OwnerKey, GroupKey
from (
select PropertyKey, BoughtDate, OwnerKey, GroupKey,
RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]
from PropertyOwners
) as result
where result.[Rank]=1 and result.[OwnerKey]=@ownerKey
It is taking 2-3 seconds to get the records which is too slow, similar time it is taking as I try to get the records using the GroupKey. But when I tried to get the records for the PropertyKey with the same query, it is executing in 10 milliseconds.
May be the slowness is due to as OwnerKey/GroupKey in the table can be null and sql server in unable to index it. I have also tried to use the Indexed view to pre ranked them but I can't use it in my query as Rank function is not supported in indexed
view.
Please note this table is updated once a day and using Sql Server 2008 R2. Any help will be greatly appreciated.create table #result (PropertyKey int not null, BoughtDate datetime, OwnerKey int null, GroupKey int null, [Rank] int not null)Create index idx ON #result(OwnerKey ,rnk)
insert into #result(PropertyKey, BoughtDate, OwnerKey, GroupKey, [Rank])
select PropertyKey, BoughtDate, OwnerKey, GroupKey,
RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]
from PropertyOwners
go
declare @ownerKey int = 1
select PropertyKey, BoughtDate, OwnerKey, GroupKey
from #result as result
where result.[Rank]=1
and result.[OwnerKey]=@ownerKey
go
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
Updating PK with same value - effect on CASCADE UPDATE
Hello,
I would like to understand how sql server 2008 deals with cascade updates
For example I have
Parent table: Employee with column Id as varchar(20) primary key
Child table with IdEmployee as varchar(20) foreign key
I set up Cascade Update for those two tables, meaning any change to primary key in Employee table will cause update in child table rows that match affecting Id
Scenario 1:
Update Employee
set Id = 'ABC',
Name = 'something new'
where Id = 'CCC'
Result of child table: all rows with foreign key IdEmployee and value of 'CCC' are updated. Expected behavior.
Scenario 2:
Update Employee
set Id = 'ABC',
Name = 'something new 2'
where Id = 'ABC'
This time, i am doing something different. I am beside update of column Name with new value, also update primary key but
with SAME value
Question is: what is going to happen to child rows? Are they ALL going to UPDATE due to CASCADE UPDATE
So far, what i did in order to find solution is:
1. I put an timestamp column in child table that should update each time row gets updated
2. I put a trigger for update event on child table that will write something to some log table
*After I set up those two I ran example like above just to be sure timestamp gets changed as well trigger is being fired
Results of updating PK with same value:
1. Timestamp didnt change
2. Trigger didnt fire
Is this enough to make conclusion that updating primary key with same value ALONG with updating some other columns won't
affect child tables with UPDATE CASCADE ON
Update:
Database is CI AS collation
If i do following
Update Employee
set Id = 'abc',
Name = 'something new'
where Id = 'ABC'
1. Timestamp will change
2. Trigger will fire
Conclusion: Case sensitive is important here!
Thank you very much in advance
Milos>> would like to understand how sql server 2008 deals with cascade updates <<
Your posting has a number of conceptual errors.
1. The terms “parent” and “child” are not RDBMS; they are used in network databases. We have “referenced” and “referencing” tables; they can be the same table.
2. A table models a SET of things, so there is no “Employee” table unless you truly have a one-man company. We want a collective or plural name for the SET/table. A better name is “Personnel” for this table.
3. Her is no such thing as a generic “id” in RDBMS; it has to be “<something in particular>_id” to be valid. Identifiers are usually fixed length
4. It is very, very rude not to post DDL on a forum. You also do not know the ISO-11179 Rules for data element names. They do not change names from table to table! Does your name change whenever you use it in a new place?? NO! Same principle with data.
5. The ISO standard uses “<property>_<attribute property>” syntax, no the old PascalCase.
6. Why did you post a useless narrative? How do we compile “I SET up Cascade UPDATE for those two tables,..” to test it??
CREATE TABLE Personnel
(emp_id CHAR(20) NOT NULL PRIMARY KEY,
emp_name VARCHAR(25) NOT NULL,
CREATE TABLE Health_Plan
(health_plan_acct CHAR(20) NOT NULL PRIMARY KEY,
emp_id CHAR(20) NOT NULL
REFERENCES Personnel(emp_id)
ON UPDATE CASCADE
ON DELETE CASCADE,
Scenario 1:
UPDATE Personnel
SET emp_id = 'ABC',
emp_name = 'something new'
WHERE emp_id = 'CCC';
Result of child table: all rows with foreign key emp_id and value of 'CCC' are updated. Expected behavior.
Scenario 2:
UPDATE Personnel
SET emp_id = 'ABC',
emp_name = 'something new 2'
WHERE emp_id = 'ABC';
This time, I am doing something different. I am beside UPDATE of column emp_name with new value, also UPDATE PRIMARY KEY but
with SAME value.
>> Question is: what is going to happen to child [sic: referencing] rows? Are they ALL going to UPDATE due to CASCADE UPDATE. <<
SQL uses a set-oriented model, so the whole table is updated as a unit of work in theory.
So far, what I did in order to find solution is:
>> I put an timestamp column in child [sic: referencing] table that should UPDATE each time row gets updated <<
Why? It is not in the SET clause list; it cannot change. As an aside, The T-SQL TIMESTAMP is not the ANSI/ISO TIMESTAMP; it is DATETIME2(n) in T-SQL. The old TIMESTAMP is being deprecated because it stinks both in concept and implementation.
>> I put a trigger for UPDATE event on child [sic: referencing] table that will write something to some log table.<<
TRIGGERs are fired by what is called a “database event” shown in the ON [DELETE | UPDATE] clause. T-SQL adds INSERT as an event. An update to any value or to no value at all is still an update. Depending on the collation, case may or may not matter in the final
outcome.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Document library view: Group by a column with multiple values
I have a document library which has a managed metadata column.
I would like to create a view which groups the documents by this managed metadata column.
The managed metadata column can have multiple values.
I know that this is not possible with SharePoint's group by, since it only accepts those columns which can have only one single value.
But is this possible to accomplish by some other means, e.g. Content query web part? Or is there perhaps a 3rd party solution to this?
Is it possible to change the group by settings somehow to allow Group by to function with columns with multiple values? <- this may be far fetched...Hi Pekch,
I'm assuming you have VS2010 to build the custom web part. From there you will need to figure out the following:
Get a SPList object for the Document Library (See below for code example)
Loop through all the documents in the SPList object
If you have audience targetting enabled, then you'll need to determine if the user has access to the document by checking the "Target_x0020_Audiences" column)
As you also want to group by metadata, you'll need to populate 2 datatables (one table with a column containing unique metadata values and another table with a metadata column and other document related columns). Link these two tables via a dataset
relation.
Set the dataset as the datasource for a repeater, add in some css and javascript for the group expand/collaspe and it should be close to what you need.
This will be a time consuming task if you don't know where to start or have problems figuring out how to perform a certain operation. So you may want to determine if the functionality you want is required or just a "nice to have". Good
luck and if I have some spare time, I'll create a blog post outlining how to do all the above.
I got the below code from a sharepoint blog sometime in the past and you can use it to retrieve a list.
You can use it like this: GetListByUrl(http://servername/Shared%20Documents/Forms/AllItems.aspx)
using Microsoft.SharePoint;
public SPList GetListByUrl(string listURL)
SPList list = null;
try
using (SPSite site = new SPSite(listURL))
if (site != null)
// Strip off the site url, leaving the rest
// We'll use this to open the web
string webUrl = listURL.Substring(site.Url.Length);
// Strip off anything after /forms/
int formsPos = webUrl.IndexOf("/forms/", 0, StringComparison.InvariantCultureIgnoreCase);
if (formsPos >= 0)
webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/', formsPos));
// Strip off anything after /lists/
int listPos = webUrl.IndexOf("/lists/", 0, StringComparison.InvariantCultureIgnoreCase);
if (listPos >= 0)
// Must be a custom list
// Strip off anything after /lists/
webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/', listPos));
else
// No lists, must be a document library.
// Strip off the document library name
webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/'));
// Get the web site
using (SPWeb web = site.OpenWeb(webUrl))
if (web != null)
// Initialize the web (avoids COM exceptions)
string title = web.Title;
// Strip off the relative list Url
// Form the full path to the list
//string relativelistURL = listURL.Substring(web.Url.Length);
//string url = SPUrlUtility.CombineUrl(web.Url, relativelistURL);
// Get the list
list = web.GetList(listURL);
catch { }
return list; -
To overcome column with null value-urgent
hai all,
when i query i get column with null value.
how to solve it?
thank in advance.
rcs
SQL> DESC SCOTT.CB1;
Name Null? Type
ID NUMBER
SUPCODE NUMBER
SUPLNAME VARCHAR2(100)
NAME VARCHAR2(100)
ITEMCODE VARCHAR2(10)
RECDOC NUMBER
RECDATE VARCHAR2(10)
TOTVALUE NUMBER
QTY NUMBER
CB_IPNO NUMBER
CB_VNNO NUMBER
CB_VDT VARCHAR2(10)
CB_AMT NUMBER
RECDOC_GR VARCHAR2(30)
RECDATE_GR DATE
SUPCODE_GR VARCHAR2(10)
TABLE LOOK LIKE THIS (NOT ALL DATA IN SAME ROW, BECUSE I INSERTED LAST 3 COLUMN VALUES):
ID SUPCODE SUPLNAME NAME ITEMCODE RECDOC RECDATE TOTVALUE QTY CB_IPNO CB_VNNO CB_VDT CB_AMT RECDOC_GR RECDATE_GR SUPCODE_GR
2015 AAAA 04117 9083 10545.6 78
2016 BBBB 04609 9087 25200 3600
2017 GGGG 04609 9088 28175 4025
2018 36591371.64 2565017.27
00001/07-08 02/04/2007 14020362
00002/07-08 02/04/2007 14020362
00003/07-08 02/04/2007 14010254
00004/07-08 02/04/2007 14010254
00005/07-08 02/04/2007 14021458
SQL> SELECT DISTINCT ID, SUPCODE_GR, NAME, ITEMCODE, RECDOC, RECDATE_GR, TOTVALUE, QTY FROM SCOTT.CB
1;
ID SUPCODE_GR
NAME
ITEMCODE RECDOC RECDATE_G TOTVALUE QTY
1
PRO.AT.ALU.POWDER UNCOATED
04609 15 51975 7425
2
PEN, GEL PEN
07969 17 154 11
ID SUPCODE_GR
I NEED RESULT AS FOLLOWS (ALL RESPECTIVE DDATA IN ONE LINE NOW NOT LIKE THAT):
ID SUPCODE SUPLNAME NAME ITEMCODE RECDOC RECDATE TOTVALUE QTY CB_IPNO CB_VNNO CB_VDT CB_AMT RECDOC_GR RECDATE_GR SUPCODE_GR
2015 AAAA 04117 9083 10545.6 78 00001/07-08 02/04/2007 14020362
============Even accounting for the formatting, I'm not sure I even understand the question. It could be any number of different problems or non-problems.
-
Pre-populating a date/time column with the value entered in the last added item
I have a list with a column called "expected finish date". Whenever the user adds the very first item in a list, he/she should have to enter a value for this column.
I want to make all new item entries to pre-poplate this field with the value entered in the previously added item. This way, he/she wont have to re-enter the date every time (which rarely changes). How can this be done?could create a second list ("state") with column ("default finish date")...
create a workflow on main list... if column is blank/empty, pull from second list... otherwise, update second list with the value that was entered.
Or, customize the form (InfoPath or JavaScript)
Scott Brickey
MCTS, MCPD, MCITP
www.sbrickey.com
Strategic Data Systems - for all your SharePoint needs -
Update column based on values of same table
I have table T1 with 4 columns 'col1','col2','col3','col4', 'col5','col6' as follows
Col1 Col2 Col3 Col4 Col5 Col6
1111 City1 C AA DDD A1
2222 City 1 DD HHH A1
3333 City2 B EE OOO
4444 City 1 B JJ SSS A1
5555 City2 C KK VVV
6666 City2 RR QQQ
7777 City2 B XX BBB
I have already updated Column 6with value ‘A1’ where Column 2 is ‘City1’.
Now I want to update col 6 where col2 is ‘S’ with following conditions
If Col 3 = ‘B’ then Col6 should be = col4
else it should be = col5SET col6=DECODE(col3,'B',col4,col5)
WHERE col2='S' -
Update column with parent child relationships
Hi,
i need to update a column with parent child relationship.
Please provide the possible queries..
Gobi..Hi,
Depending of the objective and the size of the tables, personally, for maintenance purposes, I preferred duplicate the parent with the new column value and duplicate the child records with this same new value. Other alternative is disable the foreign key temporarily.
You can take a look on this link below too:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:5773459616034
Cheers -
ORA-01400 - not null column with default value and item with authorization
I've searched - I would think someone has run into this. APEX 3.0.0.00.20 - I've created a simple form on a table. One of the column is a not null column with a default value. I have a select list on that item, but it has security on it - authorization scheme. So, it checks the user and if that user isn't of the right role, it will not even display that item. However, APEX appears to still send in the column in its sql! So, the default value is useless, it sends in null each time. Even if I set the default at the Item level, I get null. Argg. That's got to be a bug...
In debug, I do not see the item listed at all. It's not used. That's fine - but why is it trying to insert the value? I would think it would leave it off??? I think because the item is associated with a database column. But, getting around this is ugly. Having to create a hidden item for each one, and then check to see if I need to take the list value... horrible. Any way to get around this???I should add - I guess I can always put my own custom process in to replace the DML. Just seems like a simple thing - if the value doesn't appear on the debug, isn't set with any default value... don't include it in the DML.
-
How to Add column with default value in compress table.
Hi ,
while trying to add column to compressed table with default value i am getting error.
Even i tried no compress command on table still its giivg error that add/drop not allowed on compressed table.
Can anyone help me in this .
Thanks.Aman wrote:
while trying to add column to compressed table with default value i am getting error.This is clearly explain in the Oracle doc :
"+You cannot add a column with a default value to a compressed table or to a partitioned table containing any compressed partition, unless you first disable compression for the table or partition+"
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_3001.htm#sthref5163
Nicolas. -
Row To Column with distinct values
Hi Oracle Gurus,
Please help me on this regard.
A table has columns statuscode,reasoncode,date with valid values as
statuscode -> status1,status2,status3,status4,status5
reasoncode -> a,b,c,d,e
Date will be passed by runtime.
Requirement is to take the stage report of statuscode by reasoncode.
i.e., if status1 has value in reason it has to show the count else return null for eg. if status1 statuscode has a, b reasoncode report wil show like below.
a b c d e
status1 1 1
status2 2 2 1
status3 4 5 5 2 3
status4 3 2 2
status5 2 2
Advanace thanx for the GurusIsn't this a duplicate to the following thread posted by another user?
Rows into columns -
OBIEE 10g - Logical column with static value
I created a logical column with static numeric value in it and added it to presentation layer. The column is not showing up in Answers. All other columns I added are showing up. The issue is with this one only.
I have verified permissions on this column in presentation layer. I tried reloading server metadata in answers, restarting all services but it didn't help.
One thing I noticed this column is showing fx icon instead of Σ icon.Kid,
The fx means it is a calculated column/formula and the sigma means that you've added some aggregation type to the column.
Either way it shouldn't matter and your column should be showing up.
I would attempt to create a new column and in the fx field try entering static text and see if that allows the column to be visible after dragging it to the presentation layer subject area.
Also what is the value that you are adding? -
JCA adapter doesnt update MarkReadColumn with correct value
Hi,
I've created a JCA adapter in the SOA suite which polls a certain database. The poll works perfect only during configuration I set it to do a logical delete. My JCA looks like:
<adapter-config name="SchoolFitListener" adapter="Database Adapter" wsdlLocation="../WSDL/SchoolFitListener.wsdl" xmlns="http://platform.integration.oracle/blocks/adapter/fw/metadata">
<connection-factory location="eis/DB/SchoolFit" UIConnectionName="SchoolFit" adapterRef=""/>
<endpoint-activation portType="SchoolFitListener_ptt" operation="receive">
<activation-spec className="oracle.tip.adapter.db.DBActivationSpec">
<property name="DescriptorName" value="SchoolFitListener.PollSchoolfitPolltable"/>
<property name="QueryName" value="SchoolFitListenerSelect"/>
<property name="MappingsMetaDataURL" value="SchoolFitListener-or-mappings.xml"/>
<property name="PollingStrategy" value="LogicalDeletePollingStrategy"/>
<property name="MarkReadColumn" value="MESSAGE_READ"/>
<property name="MarkReadValue" value="READ"/>
<property name="MarkUnreadValue" value="UNREAD"/>
<property name="PollingInterval" value="60"/>
<property name="MaxRaiseSize" value="1"/>
<property name="MaxTransactionSize" value="10"/>
<property name="NumberOfThreads" value="1"/>
<property name="ReturnSingleResultSet" value="false"/>
</activation-spec>
</endpoint-activation>
</adapter-config>When I look in the log, it does the update only with the wrong value:
UPDATE POLL_SCHOOLFIT_POLLTABLE SET MESSAGE_READ = ? WHERE (((((((((((((MESSAGE_TYPE = ?) AND (MESSAGE_READ = ?)) AND (EMPLID = ?)) AND (SF_ID = ?)) AND (VOORNAAM = ?)) AND (ACHTERNAAM = ?)) AND (VOLLEDIGE_NAAM = ?)) AND (STRAAT = ?)) AND (HUISNR = ?)) AND (POSTCODE = ?)) AND (WOONPLAATS = ?)) AND (GEBOORTEDATUM = ?)) AND (BSN = ?))
[2011-06-15T15:34:17.067+02:00] [osb_server1] [TRACE] [] [] [tid: [ACTIVE].ExecuteThread: '7' for queue: 'weblogic.kernel.Default (self-tuning)'] [userId: weblogic] [ecid: 0000J2JW9fx7y0G_yx0FyW1Dvr150008l6,0] [SRC_CLASS: org.eclipse.persistence.internal.databaseaccess.ParameterizedSQLBatchWritingMechanism] [APP: JCA Transport Provider] [dcid: ae78371b7bf314eb:253fe233:1306f4ea111:-8000-00000000000149e2] [SRC_METHOD: executeBatchedStatements] bind => [UNREAD, C, UNREAD, SF9905731, 131983, John, Doe, John Doe, DowningStreet, 79, 57112, NY, 15-3-1994, 1234567890]Can anyone tell me why it does an update with the wrong value?
Much thanks!Found it. Marked too many fields as PK's during wizard so it couldn't find the right row for the update.
-
Hello all.
I have a dropdown list with values and a button on page1, and I have an layout on page2.
The problem is that I want that the layout on page2 could be updated depending on the value of page1.
Could anyone help me!!
Vitor Ramalhoyou can pass the value of Page 1 to Page 2 via Navigation->SET_PARAMETER(name = 'your_variable' value = 'Value') &
then based on the value u received from Page 1, update the Page 2. can you be more specific to help you more.
TO show values in Layout use below syntax:
<%= your_variable %>
Note: DOnt forget to set the "Auto" checkbox in Page2 parameter.
Raja T
Message was edited by:
Raja Thangamani
Maybe you are looking for
-
System Log Event ID 4321 every 30 seconds, system name conflict for a name not in use
-- Symptom -- System event log shows an error with event ID 4321 every 30 seconds: The name "pac-1 :2d" could not be registered on the interface with IP address 172.20.51.206. The computer with the IP address 172.20.21.2 did not allow the na
-
Possible solution to many of the issues here
Hi - I have run into a number of the issues that seen to have cropped up in the last few weeks - posting comments and a question of my own. I was having the following issues: No printing iCal No saving calendars Calendars missing Issues with creating
-
How do I download a Adobe PDF file and get it converted to a Word document?
How do I download a Adobe PDF file and get it converted to a Word document?
-
Hi,somebody knows what tables use the transaction pr05(travel expense manager), I need the data of receipts but I don't find what tables to use.
-
How to change Self Monitoring Thresholds in SOLMAN 7.1 SP8?
Hello Expert, I'm wondering if there is an option to change Self Monitoring Thresholds in SOLMAN 7.1 SP8? I'm getting so many SOLMAN Self Monitoring alert's emails, so looking forward to adjust the thresholds (if this is possible at all)? Your help i