there is two similar fields (Size) with the same datatype, I want to make a relation in a way if I change the value in (TableX.Size) the same value will be applied to (TableY.Size).
Hi - I'm in a situation with a very large table, and trying to run an update that, any way I've approached it so far, seems to be taking unnacceptably long to run. Table has about 20 million rows, looks something like this:
ID - int, identity Type - varchar(50) PurchaseNumber - varchar(50) SalesAmount - Money
ID Type PurchaseNumber SalesAmount 1 A 3834AA38384 20.32$ 2 B 3834AA38384 11837.32$ 3 C 3834AA38384 666.32$ 4 C 887DF88U01H 23423.32$ 5 A 887DF88U01H 12.32$ 6 B OI83999FH28 4747.1$ 7 D 38438495985 9384.6 8 E 02939DDJJWI 22.22$ 9 F 07939SDFDF2 33.33$
The goal of the update is to make the [Type] uniform across [PurchaseNumbers], according to the max sales amount. For each PurchaseNumber a, set the type = the type of the row that has the MAX salesAmount. If there is only one entry for PurchaseNumber, leave the type alone. Expected update after completion would look like this:
ID Type PurchaseNumber SalesAmount 1 B 3834AA38384 20.32$ 2 B 3834AA38384 11837.32$ 3 B 3834AA38384 666.32$ 4 C 887DF88U01H 23423.32$ 5 C 887DF88U01H 12.32$ 6 B OI83999FH28 4747.1$ 7 D 38438495985 9384.6 8 E 02939DDJJWI 22.22$ 9 F 07939SDFDF2 33.33$
I got this out of a warehouse, and it definitely isn't normalized well. Was considering breaking down into a better model, but I'm not yet sure if that would make the update easier.
I've been approaching this with sub-queries (finding all the PurchaseNumbers with more then one entry, then the max sales purchase of that purchase Number, then the type of that purchase number and sales amount to update all of that purchase number) but this not only ends up a little messy, but also very slow.
The only other detail that may be important is that out of the 20 million total rows, about 19.5 million purchaseNumbers are unique. So, really, there are only about 500k rows I actually have to update.
I've thought of a few ways to make this work, but none of them seem fast and wanted to see if anyone had a pointer. Thanks!
I have a scenario where two tables are in a One-to-Many relationshipand I need to move the data from the Many table to the One table sothat it becomes a One-to-One relationship.I need to salvage the records from the many table and without goinginto detail, one of the reasons I can't do the opposite asthere are records in the ONE table that I need to keep even if theydon't have any child records in the MANY table.Below I created the code to create the sample tables:1- tblProducts is the ONE side table2- tblProductDetails is the MANY side table3- tblProductsResult is the RESULT I expect to get after runningsome T-SQL code4- tblProductComponents is another MANY side table to tblProducts5- tblProductComponentsResult is the RESULT I expect to get...Some of the points to consider:6- Normally all UniqueID columns are to be IDENTITY. Forthis sample i am entering the UniqueID values myself.7- I don't want to create new tables like tblProductsResultand tblProductComponentsResult. I want to update the real tables.I have created the tblxxxResult tables only for this post.8- The goal is to update the name of the Product by giving it thename of the first matching Name from tblProductDetails.9- If there are more than one entry in tblProductDetails for eachProduct, then I need to create new Products inheriting the originalProduct's information including its child records from tblProductComponents.If you run the code and open the tables it will be much clearerto visually see what I want to achieve.CREATE DATABASE MyTestDBGOUSE MyTestDBGOCREATE TABLE [dbo].[tblProducts] ([UniqueID] [int] NOT NULL PRIMARY KEY ,[Name] [varchar] (80) NULL,[TagNo] [int] NULL) ON [PRIMARY]GOINSERT INTO tblProducts VALUES (1, 'ABC', 55)INSERT INTO tblProducts VALUES (2, 'DEF', 66)INSERT INTO tblProducts VALUES (3, 'GHI', 77)INSERT INTO tblProducts VALUES (4, 'JKL', 88)CREATE TABLE [dbo].[tblProductDetails] ([UniqueID] [int] NOT NULL PRIMARY KEY ,[Name] [varchar] (80) NULL,[ProductID] int) ON [PRIMARY]GOINSERT INTO tblProductDetails VALUES (1, 'ABC1', 1)INSERT INTO tblProductDetails VALUES (2, 'DEF', 2)INSERT INTO tblProductDetails VALUES (3, 'GHI', 3)INSERT INTO tblProductDetails VALUES (4, 'GHI2', 3)INSERT INTO tblProductDetails VALUES (5, 'GHI3', 3)INSERT INTO tblProductDetails VALUES (6, 'JKL2', 4)INSERT INTO tblProductDetails VALUES (7, 'JKL', 4)INSERT INTO tblProductDetails VALUES (8, 'JKL3', 4)INSERT INTO tblProductDetails VALUES (9, 'JKL4', 4)CREATE TABLE [dbo].[tblProductComponents] ([UniqueID] [int] NOT NULL PRIMARY KEY ,[ProductID] int,[Component] [varchar] (80) NULL) ON [PRIMARY]GOINSERT INTO tblProductComponents VALUES (1, 1, 'ABCa')INSERT INTO tblProductComponents VALUES (2, 1, 'ABCb')INSERT INTO tblProductComponents VALUES (3, 1, 'ABCc')INSERT INTO tblProductComponents VALUES (4, 2, 'DEFa')INSERT INTO tblProductComponents VALUES (5, 2, 'DEFb')INSERT INTO tblProductComponents VALUES (6, 2, 'DEFc')INSERT INTO tblProductComponents VALUES (7, 2, 'DEFd')INSERT INTO tblProductComponents VALUES (8, 3, 'GHIa')INSERT INTO tblProductComponents VALUES (9, 4, 'JKLa')INSERT INTO tblProductComponents VALUES (10, 4, 'JKLb')CREATE TABLE [dbo].[tblProductComponentsResult] ([UniqueID] [int] NOT NULL PRIMARY KEY ,[ProductID] int,[Component] [varchar] (80) NULL) ON [PRIMARY]GOINSERT INTO tblProductComponentsResult VALUES (1, 1, 'ABCa')INSERT INTO tblProductComponentsResult VALUES (2, 1, 'ABCb')INSERT INTO tblProductComponentsResult VALUES (3, 1, 'ABCc')INSERT INTO tblProductComponentsResult VALUES (4, 2, 'DEFa')INSERT INTO tblProductComponentsResult VALUES (5, 2, 'DEFb')INSERT INTO tblProductComponentsResult VALUES (6, 2, 'DEFc')INSERT INTO tblProductComponentsResult VALUES (7, 2, 'DEFd')INSERT INTO tblProductComponentsResult VALUES (8, 3, 'GHIa')INSERT INTO tblProductComponentsResult VALUES (9, 4, 'JKLa')INSERT INTO tblProductComponentsResult VALUES (10, 4, 'JKLb')INSERT INTO tblProductComponentsResult VALUES (11, 5, 'GHIa')INSERT INTO tblProductComponentsResult VALUES (12, 6, 'GHIa')INSERT INTO tblProductComponentsResult VALUES (13, 7, 'JKLa')INSERT INTO tblProductComponentsResult VALUES (14, 7, 'JKLb')INSERT INTO tblProductComponentsResult VALUES (15, 8, 'JKLa')INSERT INTO tblProductComponentsResult VALUES (16, 8, 'JKLb')INSERT INTO tblProductComponentsResult VALUES (17, 9, 'JKLa')INSERT INTO tblProductComponentsResult VALUES (18, 9, 'JKLb')CREATE TABLE [dbo].[tblProductsResult] ([UniqueID] [int] NOT NULL PRIMARY KEY ,[Name] [varchar] (80) NULL,[TagNo] [int] NULL) ON [PRIMARY]GOINSERT INTO tblProductsResult VALUES (1, 'ABC1', 55)INSERT INTO tblProductsResult VALUES (2, 'DEF', 66)INSERT INTO tblProductsResult VALUES (3, 'GHI', 77)INSERT INTO tblProductsResult VALUES (4, 'JKL', 88)INSERT INTO tblProductsResult VALUES (5, 'GHI2', 77)INSERT INTO tblProductsResult VALUES (6, 'GHI3', 77)INSERT INTO tblProductsResult VALUES (7, 'JKL2', 88)INSERT INTO tblProductsResult VALUES (8, 'JKL3', 88)INSERT INTO tblProductsResult VALUES (9, 'JKL4', 88)I appreciate your assistance on this.Thank you very much
Hello...i have a table that record all the reading meter....so when i change one of the reader meter data...in logical it will automatically change the normalized fields...
Reading teble ------------------- -id[PK] -meter -normalized -date when i insert new record..i just insert data about date and meter...an normalized is automated calculate using my function..the problem is..when i have data more than one...when i try insert or update or delete data...it nee to be automatically calculate back the normalized..i know this is needed the temperory table and then reinsert back..how can i solve this problem???
Can I make a copy of my development database DEV on same SQL SERVER machine, rename it to TEST and stored procedures to be updated automatically for statements likeUPDATE [DEV].[dbo].[Company]SET [company_name] = @company_nameto becomeUPDATE [TEST].[dbo].[Company]SET [company_name] = @company_namein order not to edit each individual stored procedure for updating it ?
Hi ~ I made simple stored procedure that is to update user information following as... ALTER PROCEDURE UpdateUserProfile( @user_id uniqueidentifier, @user_firstname nvarchar(50), @user_lastname nvarchar(50), @user_birth nvarchar(20), @user_gender nvarchar(20) ) AS UPDATE user_profile SET user_firstname = @user_firstname, user_lastname = @user_lastname, user_birth = @user_birth, user_gender = @user_gender WHERE user_id = @user_id RETURN When I tried to save this procedure, I faced on "Invalid Object : UpdateUserProfile" error message. What's the problem ?
I actually work in an organisation and we have to find a solution about the data consistancy in the database. our partners use to send details to the organisation and inserted directly in the database, so we want to create a new database as a buffer database to insert informations from the partners then make an update to the main database. is there a better solution instead of that?
Hi friendsI have one Table called tblCategory.I have three Column CatID, CatName, ParentIDI have many records in this TableCatID CatName ParentID1 Cat1 0 2 Cat2 13 Cat3 14 Cat4 25 Cat5 26 Cat6 07 Cat7 68 Cat8 69 Cat9 710 Cat10 711 Cat11 8 Here I have Main Category which has ParentID 0 [ Cat1 and Cat6 ]I Have Sub categories of Cat1 Which has ParentID 1(CatID 1 of Cat1) [ Cat2 and Cat 3 ]Cat 2 has also sub category with ParentID 2 (CatID 2 of Cat2) [ Cat4 and Cat5]I want result looks like asCat1 Cat6 ->>>>>ParentID 0- Cat2 -Cat7 ->>>>>ParentID 1(CatID of Root Cat1) and ParentID 6(CatID of Root Cat6)- - Cat4 - -Cat9 ->>>>>PaerntID 2(CatID of Root Cat2) and ParentID 7(CatID of Root Cat7)- - Cat5 - -Cat10 ->>>>>PaerntID 2(CatID of Root Cat2) and ParentID 7(CatID of Root Cat7) - Cat3 -Cat8 -->>>>>ParentID 1(CatID of Root Cat1) and ParentID 6(CatID of Root Cat6)--No record --Cat11 Can anybody give me solution?Thanks
If i add a new table to my database with a stored procedure, using that same sp or another can i also add a 1-M relationship with another table that is currently in the database. Please if you can provide an example.
i want to insert null values into a column which is a foreign key It has relation form other table.Is it possible to insert null to such a field .if so please tell the synatax to insert(i mean the process)
Hello,I'm relative new to sql and databases and the last few weeks I learnedmyself a lot. I'm trying to make a hotel reservation application.I have a database with a table Booking, a table Room, a tableRoomsPerBooking. So a booking contains date/time etc and a fieldRoomsPerBookingID. The table RoomsPerBooking contains number ofpersons, unitprice etc. and a field ID and a field RoomID. The tableRoom contains data like name, notes etc.now i have two questions:First about relations:The table Booking has relationship: PK table RoomsPerBooking - ID <-->FK table Booking - RoomsPerBookingID.The table RoomsPerBookingID has relationship: PK table Room - ID <-->FK table RoomsPerBooking - RoomIDIs this relationset good for my purpose? I think it is, but I am notsure.The second question is:How do I get available rooms per nightI came this far.... what are the "some statements"?CREATE PROCEDURE dbo.GetAvailableRooms(@BeginDate DATETIME,@EndDate DATETIME)ASSELECT Room.*FROM RoomWHERE Room.ID NOT IN (SELECT DISTINCT room.IDFROM Room room JOIN RoomsPerBooking roomsPerBookingON room.ID = roomsPerBooking.RoomID--Some statements--WHERE booking.FromDate <= @EndDateAND booking.ToDate >= @BeginDate)GO
I have defined a relation between 2 tables in "database diagrams" (IDE)but when a fill my tables vith a sqldataadapter i obtaina tables without relations why??how i can reslve this problem?my code is:Dim da As New SqlDataAdapter("SELECT * FROM table1", cn)Dim ds As New DataSetda.FillSchema(ds, SchemaType.Source, "table1")da.Fill(ds, "table1")--> ds.tables(0).relations.count =0 !!!!!!!!????????!!!
HI!I have a ASPNETDB as my login databas. but now i want to connect this databas or the aspnet_user table to my table, how do i?I want to check the username in aspnet_user table and select the same username in my table?I want to write all sql code in a sql file. so i want to know how i can connect to the sql file from my c# code?I hope somebody understand me...
When we have Table1 and Table2, then we link both tables using a third table Table3 that relates n records in Table1 to n records in table2, how do we call Table3? There is a name in dataBase modeling for that, right?
hi, If I want to make one to many relationship, I put the pk of the parent as a fk in the child . like this customer table (cust_id, fname,lname) customer_order table(order_id,cust_id,qty,price)
I do understant this, but what about look up table, can I consider cust_id inthe customer_order table as a lookup field to the customer table?
I have about six different entities that can have zero or more note entities associated with them. The easy way to do this is obviously to have a different "note" table for each of the entities i.e. WorkItemNote, CustomerNote etc.. But I would much rather have a single "note" table since they would all be identical, so I came up with this design:
CREATE TABLE WorkItem ( WorkItemGuid uniqueidentifier PRIMARY KEY DEFAULT (newid()), -- rest of table declaration removed for bravity )
CREATE TABLE Customer ( CustomerGuid uniqueidentifier PRIMARY KEY DEFAULT (newid()), -- rest of table declaration removed for bravity )
CREATE TABLE Note ( NoteId int IDENTITY(1,1) NOT NULL PRIMARY KEY, ReferenceGuid uniqueidentifier NOT NULL, Text ntext NOT NULL, -- rest of table declaration removed for bravity )
This way I can get notes associated with a given entity, either Customer or WorkItem, by just selecting from the Note table with its WorkItemGuid or CustomerGuid.
My question is: Is this the best approach to what I am trying to accomplish?
(ps: Apologies if "many to one" is not the right terminology)
This is the stored procedure which I'm using. Don't get any syntax error, only not the correct output.
create procedure sp_Select_log_By_ProfileId @ProfileId int as select l.LogId, l.LogDescription, l.CreatedOn, l.LogAuthorId from Logs l inner join ProfileLogs pl on pl.LogId = l.LogId where pl.ProfileId = @ProfileId;
hi, I got confused for a moment about creating data structure for UMLcomposition (strong aggregation) relation one-to-many.I used Rose/DataModeler to do so.[Parent] <filled_diamond>-------- [Child]I got P/FK (primary key of my component is foreign key of it's container) inmy child table:Parent: PK Parent_IDChild: P/FK Parent_IDthat way I found out I got relation 1:1, I'm still not sure how to createdata structure realizing compositiona one-to-many.
Hi All, I have a little problem and i hope u will help me. Well, my problem is, i want to make a relation between 2 tables which r not in the same databse. Database D1 >>> Table T1 Database D2 >>> Table T2
So i want something like this: Table T1: ID >>> PK
Table T2: ID >>> PK Table1ID >>> FK from Table T1
so, i will have a relation between the 2 tables. Thanks in Advance,
Hi, I am new to sql and is working with sql server managment 2005 +c# 2005.
My application needs to create a blockdiagram sort of thing say if in my database i got a table 'Addition' with 'a', 'b', 'c',and the primary key addition_id, and c is related to a and b as c = a+ b.
there is stored procedure name usp_addition which contains this relation. Each time any insert or update is done this sp is executed and all the values are updated for accordingly. My problem starts in the front end where i need to draw the graphical representation of table addition.
In this graphical representation, I need to draw the labels a, b, c and the arrows from a and b which will connect to c, showing that c has a, b as inputs.
I got the label using dataset and datacolumns but hte problem is how to create the arrows the name of labels (i.e my column names from which the arrow should start and end)
How does I get the information that c as two inputs a, b. I dont need the values since i just want to view the columns in table and which column is input to another column.
Since I need to do this dynamically because my tablename, and the number and name of column would differ does any body knows how to do this.
I usually crate relation with database but not use physical relation * My question is if crate physical relation is best way or not and what advantage and disadvantage of physical relation and if it the best way to make relation
I have 2 w2k servers with different domains and On which SQL2k is running on both the Servers. Both the servers don't have any Trust Relations between them.
My questions is, Is it possible to create Linked Servers between sql servers but their Operating Systems doesn't have Trust Relationships?.
I have two tables. CREATE TABLE Service( SERVId varchar (10) NOT NULL, SERVName varchar (30) NOT NULL, SERVDesc TEXT NULL, PRIMARY KEY(SERVId) )
CREATE TABLE New( SERVId varchar (10) NOT NULL, NDId varchar (10) NOT NULL, NDName varchar (30) NOT NULL, NDDesc text NULL, PRIMARY KEY(SERVId,NDId) FOREIGN KEY(SERVId) REFERENCES Service(SERVId) )
Msg 547, Level 16, State 2 DELETE statement conflicted with COLUMN REFERENCE constraint 'FK__Newdev__SERVId__4939E6D2'. The conflict occurred in database 'test', table 'New', column 'SERVId' Command has been aborted.
The same problem occurs even if the second table i.e. new is declared as follows, i.e created with only one primary key: CREATE TABLE New( SERVId varchar (10) NOT NULL, NDId varchar (10) NOT NULL, NDName varchar (30) NOT NULL, NDDesc text NULL, PRIMARY KEY(NDId) FOREIGN KEY(SERVId) REFERENCES Service(SERVId) )
what might be the problem? But the same relation works on MS Access. Is there anyother way of declaring this kind of relationship i.e. primary and foreign key?Can anyone pl. help me in solving this problem of foreign key relation.
Is there any way to find the dependency between two datasets in ssrs report. I want to delete one of dataset but need to find if I delete that it will work or any relation with the other dataset.
Hi Group,(I am just starting with SQL Server 2005.)On SQL Server 7 I used often the nice relation schema, where I used todraw out the whole database, especially the Foreign Keys constraints.I found these relational schemas very handy to study an old database Ibuild a few years earlier that needs some updating.I tried to find such an utility in SQL Server 2005, but cannot find it.I did found the FK-constraints, but it is just an popup where I candefine them.The overview such a visual schema gave was really great and I miss it.Question: Is it gone in SQL Sevrer 2005, or do I just not know where tolook? If the latter, please guide me. :)Thanks for your time.Regards,Erwin Moller
Hi, I have heard alot of people talk about using C# for scripting withing SSIS and the answer to that question is no apparently. You can only use VBA but there is no extensive or in my respect any documentation as reference for using VBA in SSIS. I am new to VBA because i used to use jscipt and vbscript in early version of sql server. But in order to learn using VBA, I need to learn it in which there seems to be no reference in relation to SSIS. All the VBA references you find are in relation to MS Office. Is there anything i am missing or can someone show me where to go as my reference for VBA in SSIS. Its bad enough to change the scripting language but worse not to provide any reference materials for uses to get up to speed.
What for a solution is "the best" for diamon relation? Abort one constraint in table 4 and repair with trigger? Or something else?
Description in book online: Cascading Referential Integrity Constraints:
The series of cascading referential actions triggered by a single DELETE or UPDATE must form a tree containing no circular references. No table can appear more than once in the list of all cascading referential actions that result from the DELETE or UPDATE. The tree of cascading referential actions must not have more than one path to any given table. Any branch of the tree is terminated when it encounters a table for which NO ACTION has been specified or is the default.
NO ACTION is realy BAD and USELESS solution, when want to delete row in table4 every time ..
Thx a lot
Example:
Use tempdb go
IF EXISTS (SELECT * FROM dbo.SYSOBJECTS WHERE id = object_id('table4') AND OBJECTPROPERTY(id, 'IsUserTable') = 1) DROP TABLE table4 ;
IF EXISTS (SELECT * FROM dbo.SYSOBJECTS WHERE id = object_id('table2') AND OBJECTPROPERTY(id, 'IsUserTable') = 1) DROP TABLE table2 ;
IF EXISTS (SELECT * FROM dbo.SYSOBJECTS WHERE id = object_id('table3') AND OBJECTPROPERTY(id, 'IsUserTable') = 1) DROP TABLE table3 ;
IF EXISTS (SELECT * FROM dbo.SYSOBJECTS WHERE id = object_id('table1') AND OBJECTPROPERTY(id, 'IsUserTable') = 1) DROP TABLE table1 ; go
create table table1 (table1_ID integer not null primary key)
create table table2 (table2_ID integer not null primary key, table1_ID integer not null)
create table table3 (table3_ID integer not null primary key, table1_ID integer not null)
create table table4 (table4_ID integer not null primary key, table2_ID integer not null, table3_ID integer not null) go
alter table table2 add constraint fk_one foreign key (table1_ID) references table1 (table1_ID) on delete cascade on update cascade
alter table table3 add constraint fk_two foreign key (table1_ID) references table1(table1_ID) on delete cascade on update cascade
alter table table4 add constraint fk_three foreign key (table2_ID) references table2(table2_ID) on delete cascade on update cascade
alter table table4 add constraint fk_four foreign key (table3_ID) references table3(table3_ID) on delete cascade on update cascade go