Transact SQL :: Update Statement In Merge Does Not Work
Jul 29, 2015
In the following t-sql 2012 merge statement, the insert statement works but the update statement does not work. I know that is true since I looked at the results of the update statement:
Merge TST.dbo.LockCombination AS LKC1
USING
(select LKC.comboID,LKC.lockID,LKC.seq,A.lockCombo2,A.schoolnumber,LKR.lockerId
from
[LockerPopulation] A
JOIN TST.dbo.School SCH ON A.schoolnumber = SCH.type
[Code] ...
Thus can you show me some t-sql 2012 that I can use to make update statement work in the merge function?
View 3 Replies
ADVERTISEMENT
Aug 29, 2006
I am currently having this problem with gridview and detailview. When I drag either onto the page and set my select statement to pick from one table and then update that data through the gridview (lets say), the update works perfectly. My problem is that the table I am pulling data from is mainly foreign keys. So in order to hide the number values of the foreign keys, I select the string value columns from the tables that contain the primary keys. I then use INNER JOIN in my SELECT so that I only get the data that pertains to the user I am looking to list and edit. I run the "test query" and everything I need shows up as I want it. I then go back to the gridview and change the fields which are foreign keys to templates. When I edit the templates I bind the field that contains the string value of the given foreign key to the template. This works great, because now the user will see string representation instead of the ID numbers that coinside with the string value. So I run my webpage and everything show up as I want it to, all the data is correct and I get no errors. I then click edit (as I have checked the "enable editing" box) and the gridview changes to edit mode. I make my changes and then select "update." When the page refreshes, and the gridview returns, the data is not updated and the original data is shown. I am sorry for so much typing, but I want to be as clear as possible with what I am doing. The only thing I can see being the issue is that when I setup my SELECT and FROM to contain fields from multiple tables, the UPDATE then does not work. When I remove all of my JOIN's and go back to foreign keys and one table the update works again. Below is what I have for my SQL statements:------------------------------------------------------------------------------------------------------------------------------------- SELECT:SELECT People.FirstName, People.LastName, People.FullName, People.PropertyID, People.InviteTypeID, People.RSVP, People.Wheelchair, Property.[House/Day Hab], InviteType.InviteTypeName FROM (InviteType INNER JOIN (Property INNER JOIN People ON Property.PropertyID = People.PropertyID) ON InviteType.InviteTypeID = People.InviteTypeID) WHERE (People.PersonID = ?)UPDATE:UPDATE [People] SET [FirstName] = ?, [LastName] = ?, [FullName] = ?, [PropertyID] = ?, [InviteTypeID] = ?, [RSVP] = ?, [Wheelchair] = ? WHERE [PersonID] = ? ---------------------------------------------------------------------------------------------------------------------------------------The only fields I want to update are in [People]. My WHERE is based on a control that I use to select a person from a drop down list. If I run the test query for the update while setting up my data source the query will update the record in the database. It is when I try to make the update from the gridview that the data is not changed. If anything is not clear please let me know and I will clarify as much as I can. This is my first project using ASP and working with databases so I am completely learning as I go. I took some database courses in college but I have never interacted with them with a web based front end. Any help will be greatly appreciated.Thank you in advance for any time, help, and/or advice you can give.Brian
View 5 Replies
View Related
Sep 17, 2015
I have a stored procedure that runs (SQL Server 2012 (SP1) Standard Ed) daily and I never had any problem with this stored procedure. However, there is MERGE statement on the stored procedure and I see an error saying that the MERGE statement failed..Here are the stored procedure and error message:
-- FlushQueue
CREATE PROCEDURE [dbo].[FlushQueue] (@RowCount as int = 10000)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
[code]....
The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows. [SQLSTATE 42000] (Error 8672). The step failed.
Table definition:---CREATE TABLE [dbo].[ImportDefinitions]
(
[NodeName] [varchar](20) NOT NULL,
[ProcedureName] [varchar](100) NOT NULL,
[FilePrefix] [varchar](20) NOT NULL,
[ImportDelay] [int] NOT NULL CONSTRAINT [DF_ImportDefinitions_ImportDelay] DEFAULT ((0)),
[code]...
View 13 Replies
View Related
Nov 12, 2014
I was using Type 2 for one of our Fact table.... and need to put a flag to know which one is the Current record... I couldn't able to figure how to implement logic in the merge statement... This is an example Query ....I was using like this for my fact table...
Basically I need to track CustomerName and City... So I need a Currentflag (Y) for latest record....
MERGE INTO [dbo].[TargetCustomer] AS TRG
USING [dbo].[MyCustomers] AS SRC
ON TRG.[CustomerID] = SRC.[CustomerID]
AND TRG.[CustomerName]=SRC.[CustomerName]
AND TRG.[City]=SRC.[City]
[Code] .....
View 7 Replies
View Related
Oct 7, 2015
In a t-sql 2012 merge statement that is listed below, the insert statement on the merge statement listed below is not working. The update statement works though.
Merge test.dbo.LockCombination AS LKC1
USING
(select LKC.lockID,LKC.seq,A.lockCombo1,A.schoolnumber
from
[Inputtb] A
JOIN test.dbo.School SCH ON A.schoolnumber = SCH.type
JOIN test.dbo.Locker LKR ON SCH.schoolID = LKR.schoolID AND A.lockerNumber = LKR.number
[code]...
Thus would you tell me what I need to do to make the insert statement work on the merge statement listed above?
View 10 Replies
View Related
Apr 20, 2015
In order to feed a fact table of a dwh from a staging table I'm using the MERGE statement in order to control insert and update operations. It is possible that the staging table has duplicate rows respect to the fields controlled in the merge condition:
When I run the first time the MERGE statement unwanted rows could be inserted in the fact table.
Does the MERGE statement allow to manage this case or do I need to filter data from the staging table before to write them into the fact table?
View 4 Replies
View Related
May 11, 2007
Could someone tell where I can find out if it's true that duringUPDFATE SQL Serve deletes data from table, and then inserts new one.Thanks-A
View 4 Replies
View Related
Nov 8, 2015
I am new to use MERGE statement. The MERGE cannot find any match Cardnumber in the target table. It inserts row into an existing row on the target table causing SQL rejected with duplicate key not allowed. The CardNumber is defined as a primary key on the target table with no duplicate allowed. Below snippet stop when MERGE insert a row exists on the target. The source table contains multiple rows with the same Cardnumber because it is a transactional table with multiple redemptions.
If MERGE cannot handle many (source) to one (target) relationship, what other method that I can change to in order to update the target GiftCard table which keeps track of gift card balance?
Below is the error message:
Msg 2627, Level 14, State 1, Line 5
Violation of PRIMARY KEY constraint 'PK_GiftCard'. Cannot insert duplicate key in object 'dbo.GiftCard'. The duplicate key value is (63027768).
The statement has been terminated.
DDL of the target table:
CREATE
TABLE [dbo].[GiftCard](
[CardNumber] [varchar](50) NOT NULL,
[Year] [int] NULL,
[Month] [int] NULL,
[Period] [int] NULL,
[TransAmount] [decimal](10, 2) NULL,
[Code] ....
View 8 Replies
View Related
Mar 14, 2014
I am using Merge Statement. Here is my requirement, I don't want to Insert data if Client State is NY, but I want to update all data
When Not Matched
and State not in ('NY')
THEN INSERT
the problem is sometime data NY data is inserted and sometime don't.
View 4 Replies
View Related
Feb 11, 2015
Even rowchecksum is different in target from source then also update is not happening
alter Procedure SP_Archive_using_merge
AS
BEGIN
SET NOCOUNT ON
Declare @Source_RowCount int
Declare @New_RowCount int
[Code] ....
View 1 Replies
View Related
May 5, 2015
I am attempting to run update statements within a SELECT CASE statement.
Select case x.field
WHEN 'XXX' THEN
UPDATE TABLE1
SET TABLE1.FIELD2 = 1
ELSE
UPDATE TABLE2
SET TABLE2.FIELD1 = 2
END
FROM OuterTable x
I get incorrect syntax near the keyword 'update'.
View 7 Replies
View Related
Jul 10, 2015
I have this sql stored procedure in SQL Server 2012:
ALTER PROCEDURE [dbo].[CreateBatchAndSaveExternalCodes]
@newBatches as dbo.CreateBatchList READONLY
, @productId int
, @cLevelRatio int
, @nLevelRatio int
AS
set nocount on;
[Code] ....
View 4 Replies
View Related
Mar 12, 2015
I have created a Dynamic Merge statement SCD2 Store procedure , which insert the records if no matches and if bbxkey matches from source table to destination table thne it updates old record as lateteverion 0 and insert new record with latest version 1.
I am getting below error when I ahve more than 1 bbxkey in my source table. How can I ignore this.
BBXkey is nothing but I am deriving by combining 2 columns.
Msg 8672, Level 16, State 1, Line 6
The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.
View 4 Replies
View Related
Dec 8, 2006
Suppose your using Merge Replication.
2 Users in 2 locations issue updates to the same table. 1 updating 1 column and the other updating another column. Now in reality the actual Stored Procedure issuing the update statement is passed in all the possible columns that could change and builds an update statement that updates all columns even the ones that havent changed.
Will this break Merge Replications conflict tracking? Or does SQL Server 2005 Merge Replication pickup that in reality the 2 updates only in reality changed the values in 2 columns.
View 1 Replies
View Related
Jun 20, 2013
Problem Summary: Merge Statement takes several times longer to execute than equivalent Update, Insert and Delete as separate statements. Why?
I have a relatively large table (about 35,000,000 records, approximately 13 GB uncompressed and 4 GB with page compression - including indexes). A MERGE statement pretty consistently takes two or three minutes to perform an update, insert and delete. At one extreme, updating 82 (yes 82) records took 1 minute, 45 seconds. At the other extreme, updating 100,000 records took about five minutes.When I changed the MERGE to the equivalent separate UPDATE, INSERT & DELETE statements (embedded in an explicit transaction) the entire update took only 17 seconds. The query plans for the separate UPDATE, INSERT & DELETE statements look very similar to the query plan for the combined MERGE. However, all the row count estimates for the MERGE statement are way off.
Obviously, I am going to use the separate UPDATE, INSERT & DELETE statements. The actual query plans for the four statements ( combined MERGE and the separate UPDATE, INSERT & DELETE ) are attached. SQL Code to create the source and target tables and the actual queries themselves are below. I've also included the statistics created by my test run. Nothing else was running on the server when I ran the test.
Server Configuration:
SQL Server 2008 R2 SP1, Enterprise Edition
3 x Quad-Core Xeon Processor
Max Degree of Parallelism = 8
148 GB RAM
SQL Code:
Target Table:
USE TPS;
IF OBJECT_ID('dbo.ParticipantResponse') IS NOT NULL
DROP TABLE dbo.ParticipantResponse;
[code]....
View 9 Replies
View Related
Jun 16, 2015
When I run this update statement, it updates the proper badgenumbers but it only updates them to 1 when I did a count? As the data displays some of the results should be more than 1. Why did this occur?
Declare
@count int,
@Assignment varchar(100),
@fullname varchar(100),
@timeworkedtoday decimal(18,2),
@badgeNum varchar(50),
@ticket varchar(50)
[Code] ....
View 5 Replies
View Related
Oct 1, 2015
I keep getting an error of error in statement near = on this update statement. What is incorrect?
Update abcd
Set CAST(field1 As varchar(4000)) = 'Computers and 2-in-1s'
where CAST(field1 As varchar(4000)) = 'Computeres and and 2-in-1s'
View 11 Replies
View Related
Apr 21, 2015
I created this unique codes and
I need all [FRMDAT] field set to ‘12/31/2014’ in the MKLOPT table, where the [JOBCOD] in the VALUE list BELOW have a [FRMDAT] that is currently (greater than) > ‘12/31/2014’
VALUE LIST
PH00059
PH02775
PH03051
PH03305
PH03336
PH03342
PH03371
PH03992
PH03993
PH03994
View 2 Replies
View Related
Nov 11, 2015
I am trying to run the below but I get an error of 'Incorrect syntax ')'' --- I have tried every angle I can think of around the parens to fix this but nothing I do is working.
UPDATE abcdefg
SET [Date] = GETDate(),
[readytogo] =
(
CASE WHEN [customername] NOT IN (Select [customername] from [server].[database].[dbo].[view])
THEN 'Yes'
ELSE
'Needs Verification'
[code]....
View 5 Replies
View Related
Jun 4, 2015
I have used the below update query. However, its updating only the first value. Like its updating AB with volume when c.Type = ABC, similarly for CD. Its not updating based on the 2nd or the next case condition.
Update XYZ Set AB = a.Amt * (CASE WHEN c.Type = 'ABC' THEN (c.volume)
WHEN c.TYPE = 'DEF' THEN (c.volume)
WHEN c.Type = 'GHI' THEN (c.volume)
Else 0
END),
CD = CASE WHEN c.Type = 'MARGIN' THEN '4105.31'
WHEN c.Type = 'ABC' THEN '123.1'
WHEN c.Type = 'DEF' THEN '234.2'
WHEN c.Type = 'GHI' THEN '567.1'
END
from table1 a join table2 b
on a.Cust = b.Customer
join table3 c
on b.account = c.account and b.channel =c.channel
Why its not working properly? But if i use Select statement instead of update query its working properly.
View 18 Replies
View Related
Oct 8, 2015
In t-sql 2012, data is obtained from [Inputtb].lockCombo1 where it is defined as varchar(8). The data is copied to test.dbo.LockCombination.combo where the field is defined as varchar(8). This copies all the data except the last right column.
Basically a value that is '12-34-56' intially from [Inputtb].lockCombo1 ends on in st.dbo.LockCombination.combo looking like
'12-34-5'. In this case the last value of '6' is missing. I have tried to use various string functions to obtain the entire value that should be '12-34-56' and ends up looking like '12-34-5'.
Here are 2 sqls that I have used and I get the same results:
1.
UPDATE LKC
SET LKC.combo = lockCombo1
FROM [Inputtb] A
JOIN test.dbo.School SCH ON A.schoolnumber = SCH.type and A.schoolnumber =
@SchoolNumber
JOIN test.dbo.Locker LKR ON SCH.schoolID = LKR.schoolID AND A.lockerNumber =
[Code] ....
I can not change the definition of the columns since these are production settings.
Thus can you should me modified sql that will end up with the entire value of 8 characters in the [Inputtb].lockCombo1 column?
View 8 Replies
View Related
Jun 22, 2015
I have a table A and lookup table B.
table A:
| ID | FRUIT | VEGETABLE | GOOD |
--------------------------------------------
| 1 | orange | cabbage | no |
| 1 | apple | lettuce | yes |
| 1 | kiwi | broccoli | no |
| 1 | pear | kale | yes |
table B:
| ID | FRUIT | VEGETABLE |
-------------------------------
| 1 | apple | lettuce |
| 2 | pear | kale |
If the fruit and vegetable in table A is found in table B, then set the GOOD column = yes, else no.
This is what I have so far.
update tableA
set GOOD =
(case when tableA.id = C.id then 'yes'
else 'no'
end
)
from
(select tableA.id as id
from tableA A
left join tableB B on B.fruit = A.fruit
and B.vegetable = A.vegetable) C
View 6 Replies
View Related
Jul 9, 2015
I'm trying to update rows in a simple table that has a UNIQUE KEY CONSTRAINT defined on one of its columns. Here is the DDL for the table:
CREATE TABLE [dbo].[SEC_USER](
[SEC_USER_ID] [int] IDENTITY(1,1) NOT NULL,
[USER_CODE] [varchar](100) NOT NULL,
[USER_NAME] [varchar](128) NOT NULL,
[EMP_CODE] [varchar](6) NOT NULL,
[Code] ....
When trying to execute the UPDATE statement the query fails with a constraint violation error:
Violation of UNIQUE KEY constraint 'UQ__SEC_USER__A039F1EE62FE8444'. Cannot insert duplicate key in object 'dbo.SEC_USER'. The duplicate key value is (34337).
What has me baffled is that I'm not doing any insert. Also, the value that it's referencing - 34337 - doesn't exist in the table at all. I'd rather not drop the constraint.
View 8 Replies
View Related
Sep 9, 2015
My current proc updates(updates using joins of two or three tables) millions of records as per the condition provided for each department.
However, when the proc fails it writes to a ErrorTable, ERROR_MESSAGE(), ERROR_SEVERITY() and which department has failed.
Since the records are updated keeping the selected departments in loop, I get the department in a temp variable.Now, I was asked to log the specific record where the failure was occured.Something like log the identity column value or primary key value which record has failed.
View 2 Replies
View Related
Apr 20, 2015
I have this update statement that works for one record. How do I write it to include multiple records at once. Please see sample below.
update
mklopt
set
FRMDAT =
'12/31/2014'
where
JOBCOD =
'PH14789'
I also want to include the following instead of running it one at a time
PH17523
PH17524
PH17525
PH17553
PH17555
PH17556
PH17557
PH17558
PH17571
PH17573
PH17574
PH17575
PH17576
PH17577
PH1757
View 9 Replies
View Related
May 1, 2015
SQL Ver: 2008 (not r2)
Problem: The following code returns correct results when moving variable declarations and update statement outside a stored procedure, but fails to return a value other than zero for the "COMPANY TOTAL" records. The "DEPT TOTAL" result works fine both in and outside the sp.This may have to do with handling NULL values since I was getting warning message earlier involving a value being eliminated by an aggregate function involving a NULL. I only got this message when running inside the sp, not when running standalone. I wrapped the values inside the SUM functions with an ISNULL, and now return a zero rather than NULL for the "COMPANY TOTAL" records when running inside SP.All variable values are correct when running.
SQL CODE:
DECLARE
@WIPMonthCurrent date = (SELECT TOP 1 WIPMonth FROM budxcWIPMonths WHERE ActiveWIPPeriod = 'Y')
select @WIPMonthCurrent as WIPMonthCurrent
[code]....
View 10 Replies
View Related
Nov 5, 2015
I've have a need with SQL Server 2005 (so I've no MERGE statement), I have to merge 2 tables, the target table has 10 fields, the first 4 are the clustered index and primary key, the source table has the same fields and index.Since I can't use the MERGE statement (I'm in SQL 2005) I have to make a double step operation, and INSERT and an UPDATE, I can't figure how to design the WHERE condition for the insert statement.
View 2 Replies
View Related
Sep 4, 2006
Hello!
I have a problem with creating Merge replication between two instances of MSDE 2000. In the article http://support.microsoft.com/kb/324992/, published by Microsoft, described, that it is possible.
I am creating Merge Publication at MSDE 2000, with Distributor and Publisher configured at same machine, with options "Allow Pull Subscriptions" and "Allow Anonymous Subscriptions". There is no problem with creating of Publication. Even snapshot generation finishes successfully. Also I create a login with SQL Server Authentication and "System Administrators" database role at the publisher in order to connect to it from Subscriber.
The problem occurs, when creating anonymous pull subscription to this publication at another instance of MSDE. During initial synchronization an error occurs:
The process could not connect to Distributor '<publisher_server_name>'. Login failed for user '<login_created_at_publisher>'. Reason: Not associated with a trusted SQL Server connection. The step failed.
Although I didn't use Windows Authentication at all, so Subscriber doesn't need to connect to Distributor using trusted SQL Server connection.
What is a problem and how can I workaround?
Note: The same works correctly, if MS SQL Server used as a Publisher instead of MSDE.
Please, help!
I can provide publication and subscription creation scripts, if required.
View 1 Replies
View Related
Sep 20, 2007
Hi,
we have developped an application on pdaphone. we try to use merge replication between our sql server 2000 sp4 and sql Ce 3.0 via GPRS . Sometime that works very fine . Sometime it's a nightmare !!! nothing work . we have multiple error....
can someone tell me, what are the rules to make it work ?
can someone tell me, if it really works fine ?
thanks
View 1 Replies
View Related
Feb 18, 2006
I do realize that his could be posted in a few spots but I think the answer is in the SQL.
I have a ASP.NET page, with a SqlDataSource, Text Box and Calendar Controls. I have the textbox and calendar controls eval'ed to the same sql data source DateTime Field. The text box is formatted eval to small time and the calendars eval has no formatting.
ex:
<asp:TextBox ID="START_TIME" Text='<%# Eval("EVENT_START","{0:t}") %>' runat=server Width=200></asp:TextBox>
I want to merge the two controls; one has the date the other has the time when I update the pages data to the SqlDataSource field EVENT_START. I've tried a couple of methods, but I would like some other opinions. As Sql server only supports date and time together I am storing the two together.
I could merge the two together in the code behind on the update button's event handler or merge the two during the update query using parameters.
Not that I could get an illegal date for the calendar control, but I could get garbage from the textfield time. So I still would have to do validation on the text field before the SQL server could do the update.
There's a few ways to go about this, so I was wondering if anyone else has figured out an elegant way to handle it.
wbochar
View 1 Replies
View Related
Aug 4, 2015
I have been evaluating merge replication, 'push' subscription on SQL Server 2014. If the default resolver is used (I refer to @article_resolver parameter of sp_addmergearticle), all seems to work as expected. However if I use "Microsoft SQL Server Subscriber Always Wins Conflict Resolver" (or any other MS standard resolver for that matter), if the Subscriber is on a different machine, the merge agent invariably gives the following error: "The process could not initialize <resolver_name>. Verify that the component is registered correctly."
This does not happen if the Subscriber is on the same machine as the Publisher and Distributor.
The problem seemed to exist in SQL Server 2008 according to some posts but it has been apparently fixed since then. I've tried the following:
- @partition_options = 0, as was suggested somewhere.
- Copied ssrpub.dll (the resolver dll) to the Subscriber machine (should not really matter as this is 'push' subscription?)
- Registered ssrpub.dll with regsvr32 on the Publisher/Distributor machine.
I've also run sp_enumcustomresolvers on the Publisher machine, and it happily showed all standard resolver, including the "Microsoft SQL Server Subscriber Always Wins Conflict Resolver".
Another thought is, I'm using SQL Server Express as the Subscriber (on the remote machine). Perhaps it does not support custom resolvers? (I'm using the full SQL Server in the 'local subscriber' variant, which does work OK as I mentioned before).
Note also that if I create a new publication via SSMS, the Resolver tab of the Article Properties dialog is empty, i.e. it does not list any resolver. The same tab contains the full list of resolvers though, if opened for an existing publication.
View 2 Replies
View Related
Sep 24, 2015
I have a table that has columns like following
trans_code
gl_code
12qw3
a1235
12qw3
a6578
12qw3
t531
e34g6
gt25
e34g6
y7327
e34g6
v23409
Is there an easy way to turn this into format below ??
trans_code
gl_code_1
gl_code_2
12qw3
a1235
a6578
12qw3
a1235
[code]....
View 5 Replies
View Related
Aug 1, 2006
Hi all, I am new to transact-sql and hoped that someone here might be able to help. I have a db with a field called "part" ... part contains text in the format:
xxxxx-xx-xxxxx
(the number of x's before or after each hyphen vary) such that I could have xxx-xxxxx-xxx as the part.
Someone wrote this transact-sql to take my current "part" field and move it to three different part fields ... a,b,c
If xxxxx-xx-xxxxx was the part in the original db, then a would contain xxxxx .. b contains xx ... c contains xxxxx
Make sense? Here is the code. It doesn't work and I can't seem to figure out why! It looks like it is just trying to find the hyphens and cut out the text from that... but it fails with an error that says "invalid length parameter passed to the substring function". Note, if I take off the "-1" from each line below... then the function works but produces the wrong data.
char(45) = "-" (hyphen)
UPDATE [dbo].[parts] SET
a = SUBSTRING(part,1,CHARINDEX(CHAR(45),part)-1),
b = SUBSTRING(part,CHARINDEX(CHAR(45),part)+1,CHARINDEX(CHAR(45),RIGHT(part,LEN(part)-CHARINDEX(CHAR(45),part)))-1),
c = SUBSTRING(part,CHARINDEX(CHAR(45),RIGHT(part,LEN(part)-CHARINDEX(CHAR(45),part)))+CHARINDEX(CHAR(45),part)+1,LEN(part))
GO
Does anyone know what I can do to fix this or is it much more difficult to do than what it seems?
Thanks!
View 10 Replies
View Related