T-SQL (SS2K8) :: Query Be Rewritten With Merge Statement So That Whole Operation Is Atomic?

Sep 14, 2015

I would like to have a 'counter' table which will hold the last used number and return a new number. This is my schema:

if object_id('tempdb.dbo.#Counter', 'u') is not null drop table #Counter
go
create table #Counter (
Id int not null
)
go
if exists (select * from #Counter)
update #Counter
set Id = Id + 1
output inserted.Id
else
insert into #Counter (Id)
output inserted.Id
select 1

If the table is empty it returns 1 else it returns the next number (Id + 1). But this query is not atomic (i guess...?) so it could evaluate that the #Counter table is empty and then try to insert into the table, but inbetween someone else executes the insert also. Could this query be rewritten with the merge statement so that the whole operation is atomic?

View 9 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Comparison In The Merge Statement About Null Values?

Aug 22, 2012

I use the merge statement in a sproc to insert, update and delete records from a staging table to a production table.

In the long sql, here is a part of it,

When Matched and

((Student.SchoolID <> esis.SchoolID
OR
Student.GradeLevel <> esis.GradeLevel
OR
Student.LegalName <> esis.LegalName
OR
Student.WithdrawDate <> esis.WithdrawDate
Student.SPEDFlag <> esis.SPEDFlag
OR
Student.MailingAddress <> esis.MailingAddress)

Then update

Set Student.Schoolid=esis.schoolid,
.....

My question is how about if the column has null values in it.for example

if schoolID is null in production table is null, but in staging table is not null, will the <> return true.or if either side of <> has a null value, will it return true.

I don't want it to omit some records and causing the students records not get updated.If not return true, how to fix this?

View 9 Replies View Related

T-SQL (SS2K8) :: Merge Statement MULTIPLE INSERT Into Different Tables

Jul 23, 2014

Can we insert into multiple table using merge statement?I'm using SQL Server 2008 R2 and below is my MERGE query...

-> I'm checking if the record exist in Contact table or not. If it exist then I will insert into employee table else I will insert into contact table then employee table.

WITH Cont as
( Select ContactID from Contact where ContactID=@ContactID)
MERGE Employee as NewEmp
Using Cont as con

[code]...

View 2 Replies View Related

T-SQL (SS2K8) :: Return Primary Key From (updated) Record Of Merge Statement

Apr 16, 2014

I'm using a Merge statement to update/insert values into a table. The Source is not a table, but the parameters from a Powershell script. I am not using the Primary Key to match on, but rather the Computer Name (FullComputerName).

I am looking on how-to return the Primary Key (ComputerPKID) of an updated record as "chained" scripts will require a Primary Key, new or used.As an aside: the code below does return the newly generated Primary Key of an Inserted record.

CREATE PROCEDURE [dbo].[usp_ComputerInformation_UPSERT](
@FullComputerName varChar(50) = NULL
,@ComputerDescription varChar(255) = NULL
,@ComputerSystemType varChar(128) = NULL
,@ComputerManufacturer varChar(128) = NULL

[code]....

View 4 Replies View Related

Can This Query Be Rewritten??

Sep 27, 2007

update CMS_RISK_SCORES
set MAX_MCARA_RISK_RTE = (select max(MCARA_RISK_RTE) from XTAW0200_MEM_DTL A
where A.HIC_NUM = CMS_RISK_SCORES.HIC_NUM),
MAX_MCARD_RISK_ADJ_RTE = (select max(MCARD_RISK_ADJ_RTE) from XTAW0200_MEM_DTL A
where A.HIC_NUM = CMS_RISK_SCORES.HIC_NUM)

Can I get the same results with one join instead of two without creating a temporary table?

Thanks much.

:confused:

View 3 Replies View Related

Atomic Transaction

Oct 4, 2004

Hi all,

If I have 2 database operations
1. Update ....
2. Delete ....

I want these 2 operations to execute atomically, thus I make use of

BEGIN Transaction ...
Update ....
Delete ....
COMMIT Transaction ...

But if one of these operation fails, it locks up the database. Does anyone have a resolution for this? How do I detect sql Exceptions to release the transaction so that it doesn't lock up the database?

Thanx

James :)

View 2 Replies View Related

Statement, Operators, Operation.

Mar 21, 2007

Hi I just got a paging procedure from the internet and it’s working just fine, but I would like to return the numbers of pages too. So I used the Count() function to retrieve all records on the table and divided by the page size, but even I doing with float number, this is returning a integer number. I just started with SQL Server, does some knows what is wrong with the following code? or knows a better way to do it.
 
Declare     @Records int,
            @Pages float,
            @hey int
 
Set @Records = (Select Count(*) as 'Friends' From friends
 
Set @Pages = ((@Records) / (@PageSize))
 
Set @hey = (@Pages)
 
if @Pages > @hey
begin
@Pages = @Pages + 1
end
 
return @Pages
 
 
Thank you very much.

View 4 Replies View Related

DB Engine :: Can't Use The MERGE Statement / How To Design WHERE Condition For Insert Statement

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

Distinct Count, But Rewritten With Sum(case..)

Mar 28, 2007

It doesn't seem possibly, but maybe?
Is there a way to have an expression be used, but also benefit from using distinct on a column?

I'm looking for something like:
sum(case when dtEntered > '1-1-2006' then 1 else 0 end)
but also encorporating somehow a distinct count on UserName. So a username showing twice would only count once, and this would only be counted if the record's dtEntered date was greater than Jan 1, 2006.

The reason I'm writing the statement that way is because there are 5 columns which aggregate data by different time periods.

If it's not possible, I will just end up joining to the table multiple times, putting the date filter in the where clause.

View 3 Replies View Related

T-SQL (SS2K8) :: How To Merge Two Tables

May 27, 2014

I've One table that contains all current appointments booked as below.

RNappt_idclinic_idderived_location_idprovider_idappt_date_timeappt_date_endtime
1102186011435/27/14 8:305/27/14 9:00 AM
2102196011435/27/14 9:305/27/14 10:00 AM
3102206011435/27/14 10:305/27/14 11:00 AM
4102216011435/27/14 14:005/27/14 2:30 PM
5102226011435/27/14 16:005/27/14 4:30 PM
6102236011435/27/14 16:305/27/14 5:00 PM

for Same Clinic,location and Provider there's a schedule data for same day 24 hours

having every five mintues as below:

clinic_idderived_location_idprovider_idstart_timeendtimeunblock
601143 8:01 8:040
6011438:05 8:100
601143
60114313:0113:041
601143
60114313:5514:001
601143 1
60114317:5518:000
60114323:550:001

for rows having no start and endtime assume it as regular intervals.

So i need to show available appointment with duration one hour with the available schedule which is for every five minutes

Like My first appointment for today starts at 8:30 but 8- 8:30 is unblock so there could be an appointment but as this chunk is less than 60 so need to create it

For Schedule table below is what i've to create for temporary basis as this will be available in nightly load in a table.

DECLARE @num int=5
,@LASTtime TIME =CAST('23:55' as TIME)
,@Time TIME =CAST('00:00' as TIME)
,@Timeprev TIME =CAST('00:00' as TIME)
WHILE ( @Time<>@LASTtime)
BEGIN

[code]....

View 8 Replies View Related

T-SQL (SS2K8) :: Merge Standardized Data Dynamically?

Sep 2, 2014

I have table of standardized data that I'm merging into from an Import table.

This import table may have the [ContactName]. I one row in the import table has the contact name then every row would have the contact name.

What I'd like to be able to do is something like this in the UPDATE portion of the Merge (I don't care about the insert phase, since I can insert a null [ContactName] since I'm not overwritting an existing [ContactName]

MERGE INTO [dbo].[Standardized] AS [target]
USING [dbo].[ImportDestination]
AS [Source]
ON [Source].[Key] = [Target].[Key]
WHEN MATCHED
THEN UPDATE
SET[ContactName] = CASE WHEN source.[ContactName] IS NOT NULL THEN source.[ContactName] else target.[ContactName];

Is anything like that possible and if the code above works it would only work on a row by row bases. Is it possible to figure out if any [ContactName] has data and if so possibly overwrite an old [ContactName] with a null?

View 1 Replies View Related

T-SQL (SS2K8) :: Merge Multiple Rows In Single Row

Jul 8, 2015

I've a requirement where I need to merge multiple rows in single rows. For example in the attached image output, I need to return a single column for type Case like this.

CH0, CH1, CH2, CHX Case
CM0, CM1, CM2, CMX Mechanical

I'm using T-SQL to generate the column type. Below is my DDL.

USE tempdb
GO
CREATE TABLE ProdCodes
(Prefix char(8),
Code char(5)

[Code] ....

View 7 Replies View Related

T-SQL (SS2K8) :: MERGE Insert Not Working Into Target Table

Mar 16, 2014

I am trying to insert new records into the target table, if no records exist in the source table. I am passing user specific values for insert, but it does not insert any values, nor does it throw any errors. The insert needs to occur in the LOAN_GROUP_INFO table, i.e. the target table.

MERGE INTO LOAN_GROUP_INFO AS TARGET
USING (SELECT LGI_GROUPID FROM LOAN_GROUPING
WHERE LG_LOANID = 22720
AND LG_ISACTIVE = 1)
AS SOURCE

[Code] .....

View 8 Replies View Related

T-SQL (SS2K8) :: Delete And Merge Duplicate Records From Joined Tables?

Oct 21, 2014

Im trying to delete duplicate records from the output of the query below, if they also meet certain conditions ie 'different address type' then I would merge the records. From the following query how do I go about achieving one and/or the other from either the output, or as an extension of the query itself?

SELECT
a1z103acno AccountNumber
, a1z103frnm FirstName
, a1z103lanm LastName
, a1z103ornm OrgName
, a3z103adr1 AddressLine1
, A3z103city City
, A3z103st State

[code]...

View 1 Replies View Related

SQL 2012 :: Current Operation Cancelled Because Another Operation In Transaction Failed

Nov 20, 2013

I'm using SQL Server 2012 Analysis services in Tabular mode and connected to Oracle Database and while importing, I'm getting below error after importing some rows.

OLE DB or ODBC error: Accessor is not a parameter accessor.. The current operation was cancelled because another operation in the transaction failed.

View 1 Replies View Related

Problem On Query Operation

Apr 30, 2006

Hello, I have my table Produits :
CREATE TABLE [dbo].[Produit] ( [Produit_ID] [int] IDENTITY (1, 1) NOT NULL , [Reference] [nvarchar] (50) COLLATE French_CI_AS NULL , [Designation] [nvarchar] (50) COLLATE French_CI_AS NULL , [Quantite] [int] NULL , [PrixU] [sql_variant] NULL , [MontantHT] [sql_variant] NULL , [TVA] [sql_variant] NULL , [Facture_ID] [int] NOT NULL )GOhere is stored procedure CREATE PROC spBaseTVA_Bis
(
@Facture_ID int

)
AS

SELECT SUM(MontantHT) AS montantHT, TVA

FROM

Produit

GROUP BY TVA, Facture_ID
HAVING ( Facture_ID = @Facture_ID)
GO

My stored procedure  fill data in a datagrid with to column  TauxTVA and TVA  like this :    TauxTVA      TVA But I would like to add a theard column as (the value of the fisrt colum) *  ( the value of the second colum )     I would like to desplay data like this  :          TauxTVA      TVA    Prod       X           Y     X*Y       How can I modify my stored procedure to perform this ?     Regards  

View 3 Replies View Related

Merge Statement

Dec 28, 2003

Hello,
I have two tables: Orders and Appoitment. Each order can have up to 2 appointments. Now, I need a SELECT statement that gives me this:

ORDER APPT
1 appt1 appt2
2 appt1 appt2

and not this:

ORDER APPT
1 appt1
1 appt2
2 appt1
2 appt2

In other words, I want to merge the two appointments for each order. I tried using the merge statement but it does not work. Tried to google but saw nothing. My database is SQL server. Please help. Thanks

View 3 Replies View Related

How To Use Merge Statement

Aug 31, 2015

We have a current database table (PAF) that had a new column added to it named 'Email'. This table also has some other columns including one named [Employee Number].We also have an Excel spreadsheet that has 2 columns 'Employee Number' and 'E-mail Address'. I need to take the E-mail Address field from the spreadsheet, match it up with the employee number between the spreadsheet and PAF table, and then insert the email address into the database column.I'm guessing I would do this using a MERGE statement, correct?

View 4 Replies View Related

Merge Statement

Aug 17, 2006

Is there a merge statement in SQL Server 2000?

I want to combine update and insert statement into single statement as follows.

MERGE INTO MyTable
USING MyTempTable
ON MyTempTable.MatchingField1 = MyTable.MatchingField1
WHEN MATCHED THEN
UPDATE UpdateField1 = MyTempTable.UpdateField1
WHEN NOT MATCHED THEN
INSERT VALUES(MyTempTable.MatchingField1, MyTempTable.UpdateField1)

Currently if I try to run this stmt, it gives error "Incorrect syntax near the keyword 'INTO'."

Thanks

View 3 Replies View Related

Transact SQL :: Collation In Query Using Except Operation

May 28, 2015

when run this query 

  SELECT * FROM TABLE1
  EXCEPT 
  SELECT * FROM TABLE3

showing the below error

Msg 468, Level 16, State 9, Line 1
Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the EXCEPT operation.here columns collation of table1 is Latin1_General_CI_AS and columns collation of table3 is SQL_Latin1_General_CP1_CI_AS database collation is Latin1_ General_CI_AS.

View 12 Replies View Related

How To Make The SSMSE To Return Whole Records Without Any Close Query Form And Re-create Query Form Operation?

Dec 25, 2007

Hi,
I got a problem.
I installed Microsoft SQL Server Management Studio Express 2005 version.
And I created a Compact database.
I created an connection in SSMSE to connect the database and opened a query form.
then, i run the following sql:

Select * from Table1

It returned 3 records to me.
After that, I used program to insert record into this table.
Then i ran this sql again, it still show me 3 records.
I closed the query form, and re-created a new query form, then run the sql, it returned 4 records to me.

Why? It's very strange and difficult to operate, right?
Is there anyone know how to make the SSMSE to return whole records without any close query form and re-create query form operation?

Thanks a lot!

And Merry X'max!!!

View 4 Replies View Related

MERGE Statement Into Two Tables

Aug 21, 2012

I am trying to update values in two tables (approx 1-2 million records).

I have decided to use a MERGE statement, however have been unsuccessful to do so.

Below is an example of the statement.

The error is receive is "Incorrect syntax near '('." right after the MERGE line.

Is it not possible to use this syntax ?

Example:
[CODE]
MERGE
( SELECT a.id, b.id2
FROM TableA A
JOIN TableB B

[Code]....

View 5 Replies View Related

Sql Query Timeout, Expensive Cast Operation?

Jul 23, 2005

I need some tips to boost the performance on the following query.The problem is that it times out once in a while, and then again runsnormally in most cases.The clue is to compare a textual value stored as an image data type, but Idon't know if the cast operation could be done in another way.Any tips?SELECT DISTINCT pk_product FROM tbl_product PJOIN tbl_product_content PC ON P.pk_product = PC.fk_productJOIN tbl_content C ON PC.fk_content = C.pk_contentJOIN tbl_content_rel REL ON C.pk_content = REL.fk_contentJOIN tbl_filegroup FG ON REL.fk_filegroup = FG.pk_filegroupJOIN tbl_filegroup_file FF ON fg.pk_filegroup = FF.fk_filegroupJOIN tbl_file F ON ff.fk_file = F.pk_fileWHEREP.fk_product_type = 45 ANDCAST(CAST(f.data AS VARBINARY) AS NVARCHAR(20)) = '1234'/ted

View 1 Replies View Related

Merge Statement - Update All Data

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

Update Not Happening Using Merge Statement

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

Select And Insert Statement Merge Together

Jun 9, 2007

is there anyway i can merge select statement and insert statement together?

what i want to do is select few attributes from a table and then directly insert the values to another table without another trigger.

for example, select * from product and with the values from product, insert into new_product (name, type, date) values (the values from select statment)

View 3 Replies View Related

Insert Statement With Merge Replication.

Nov 9, 2007

Hello,

i have a little question.
Is it possible you can't perform an insert statement on a table wich is replicated with merge replication?

I set the replication up and everything works fine, but if i want to perfom an insert statement on the table, i get an error that the values i want to add aren't the same as the one in the table.

I know that merge replication creates a new column and I think that's the problem.

Can someone help me solve this or confirm that you can't perform an insert statement on a replicated table?

Masje

View 3 Replies View Related

Transact SQL :: Merge Statement Failed

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

T-SQL (SS2K8) :: AND Statement In Where Clause

Nov 13, 2014

I have someone telling me that I should have put my AND statement in the join instead of the where part, so is there a difference in the where I put it. Is there a difference in the results in any way between the two here in the results in anyway?

Example:
Given a query:
But let’s take a simple one here:

Query(1)
Select ct1.Name, ct1.address, ct1.city, ct1.state, ct1.zipcode
From cutTableA ct1 Left join cutTableA ct2
On ct1.ID = ct2.ID
Where ct1.zipcode = '14124'
AND ct1.Name = 'Bob'

Query(2)
Select ct1.Name, ct1.address, ct1.city, ct1.state, ct1.zipcode
From cutTableA ct1 Left join cutTableA ct2
On ct1.ID = ct2.ID
AND ct1.zipcode = '14124'
Where ct1.Name = 'Bob'

View 4 Replies View Related

MERGE Statement - Skipping Locked Records

Aug 27, 2012

skip locked records in a MERGE statement and output the list of skipped records.

Through the documentation, internet posts and testing, I believe it is NOT possible. MERGE acts like a single atomic DML statement, and therefore cannot avoid locked records.

I can use the READPAST hint, which will skip the row-locked records. However, it could actually insert duplicate keys in certain cases (as it is ignoring records, i would guess), which would not be acceptable.

View 1 Replies View Related

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 View Related

Transact SQL :: Current Flag On Merge Statement

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

Transact SQL :: Insert On Merge Statement Not Working

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







Copyrights 2005-15 www.BigResource.com, All rights reserved