Showing posts with label update. Show all posts
Showing posts with label update. Show all posts

Tuesday, March 20, 2012

Comparing 2 Columns Containing Null Values

Hi All.

I'm having some issues with what seems to be a simple update statement but is giving me grief when one or both of the columns I'm comparing are null. My statement (simplified) is as follows:-

UPDATE
TAB_A
SET
TAB_A.TRADCODE = TAB_B.TRADCODE
FROM
TADS_STAGE.DBO.UNCLBRAMDEPT TAB_B
JOIN
TADS.DBO.UNCLBRAMDEPT TAB_A
ON
TAB_B.BRANCODE = TAB_A.BRANCODE
AND
TAB_B.MERDCODE = TAB_A.MERDCODE
AND
(
TAB_B.TRADCODE <> TAB_A.TRADCODE
)

If either of the TRADCODE fields (or both) are null then the comparison fails to return the row to update. I've tried setting the ANSI_NULLS setting to off, this has no effect, presumably because it will only work when comparing a column to a variable or evaluating if the column is null itself.

I've considered using ISNULL, but if one of the columns happens to contain the value that I specify as the replacement value then the comparison will result true and not include the row.

I'd be grateful for any pointers!

Thanks in advance

Sorted it :)

I've used the ISNULL(exp,'') function, as I'm not bothered about updating nothing ('') to null and vice versa.

Just got to go back and alter all 60 scripts now

Nick

|||

Nick Colebourn wrote:

I've considered using ISNULL, but if one of the columns happens to contain the value that I specify as the replacement value then the comparison will result true and not include the row.

In this type of situation you would replace your ISNULL with some impossible calue that would never come up. Here are some other ideas:

1. You only want to update Tab_A with Tab_B's value if they're different. Why not just update it all the time?

Cons: Slower Update, More Locks, More overhead if set to full recovery mode.

UPDATE
TAB_A
SET
TAB_A.TRADCODE = TAB_B.TRADCODE
FROM
TADS_STAGE.DBO.UNCLBRAMDEPT TAB_B
JOIN
TADS.DBO.UNCLBRAMDEPT TAB_A
ON
TAB_B.BRANCODE = TAB_A.BRANCODE
AND
TAB_B.MERDCODE = TAB_A.MERDCODE

2. Make your JOIN even more complicated

UPDATE
TAB_A
SET
TAB_A.TRADCODE = TAB_B.TRADCODE
FROM
TADS_STAGE.DBO.UNCLBRAMDEPT TAB_B
JOIN
TADS.DBO.UNCLBRAMDEPT TAB_A
ON
TAB_B.BRANCODE = TAB_A.BRANCODE
AND
TAB_B.MERDCODE = TAB_A.MERDCODE
AND
(
(TAB_B.TRADCODE IS NULL AND TAB_A.TRADCODE IS NOT NULL)

OR (TAB_B.TRADCODE IS NOT NULL AND TAB_A.TRADCODE IS NULL)

OR TAB_B.TRADCODE <> TAB_A.TRADCODE
)

|||

Hi Jared,

Thanks for your reply. I think I'm going to take a multi faceted approach to this, some of my tables are only a few thousand rows, so I'll probably just do the full update, and some are 20 million rows or more, so I'll spend the time writing the intricate where clauses or experimenting with the ISNULL function.

Cheers for taking the time to respond.

Nick

Monday, March 19, 2012

Compare two databases and update objects?

Is there a way to compare two databases one being an old
database and the second being a new database, I will
update the old database's objects to match the new database's
objects?

Is there SQL code that could do this easily?

How do you do this if you deal with the same scenario?

Thank youserge (sergea@.nospam.ehmail.com) writes:
> Is there a way to compare two databases one being an old
> database and the second being a new database, I will
> update the old database's objects to match the new database's
> objects?
> Is there SQL code that could do this easily?

The standard recommendation is to look at SQL Compare from Red Gate.

> How do you do this if you deal with the same scenario?

I'm avoiding it by having my code under version control, and keeping
track of what I shipped. Our load tool actuall has its own set of tables
to do this.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||DB Ghost is a tool that will compare databases and upgrade a target
database to make it match a source.

It also integrates with any source control system so the 'source'
database becomes a simple set of drop/create scripts. The power of
this approach is that it enables any size of development team to work
on the schema under source control at the same time using the same
mechanism that they do for other application code such as C#, Java, VB,
C++ etc. This provides you with a full audit trail of who made what
changes to the schema, when and why.

This process is one that delivers more as your development needs
increase. For example it doesn't matter how many developers work on
the scripts in source control, the amount of time required to extract
all the scripts and perform the upgrade doesn't noticeably increase.
Also, this process works perfectly with parallel development as it
means that concepts such as isolated worksets and merges between code
lines becomes as easy as it is with normal application code. Try doing
parallel development with delta scripts, it is a completely error prone
manual process of looking through the delta scripts to work out what
has been changed!

Diff tools such as SQL Compare are great at what they do but,
ultimately, they are really just there to get you out of trouble.

This trouble is normally caused by not having proper processes and
tools to control changes to your schema.

DB Ghost plus any source control system gives you such a process.

Malcolm
www.dbghost.com
Build, Compare and Synchronize = Database Change Management for SQL
Server

Sunday, March 11, 2012

Compare feilds in seperate databases on seperate servers

Hi,
I want to run an update script where a field in a table in a database on a
server is equal to another field in a table in a database on a seperate
server. Here are the details:
Server 1:
Server name - Server1\Logi
Database - Ascent
Table - _customers
Field - email
Server 2:
Server name - Server2\Web
Database - ProductCart
Table - customers
Field - email
I want to update a field called 'flag' to equal 1 where the email addresses
are equal.
Can anyone help?To do this right we'd have to see more DDL - particulary interested in keys.
ML
http://milambda.blogspot.com/|||Hi
assuming you are on Server1\Logi, you can do something like
sp_addlinkedserver Web, @.srvproduct='', @.provider='SQLNCLI',
@.datasrc='Server2\WEB'
update _customers set flag = 1
from _customers a inner join Web.ProductCart.dbo.customers b on a.email =
b.email
exec sp_dropserver Web
Note that you should take care about proper credentials when connecting to
the linked server - read BOL about sp_addlinkedserver sproc. It is possible
also that it might be better to join tables on other column[s], but you did
not give any info on this.
HTH
Peter|||Hi Peter,
Thanks for the reply. I ran your script but got the following error:
Server: Msg 446, Level 16, State 9, Line 4
Cannot resolve collation conflict for equal to operation.
Any ideas what this means?
Darren
"Rogas69" <rogas69@.no_spamers.o2.ie> wrote in message
news:OAH9afjAGHA.1460@.TK2MSFTNGP14.phx.gbl...
> Hi
> assuming you are on Server1\Logi, you can do something like
> sp_addlinkedserver Web, @.srvproduct='', @.provider='SQLNCLI',
> @.datasrc='Server2\WEB'
> update _customers set flag = 1
> from _customers a inner join Web.ProductCart.dbo.customers b on a.email =
> b.email
> exec sp_dropserver Web
> Note that you should take care about proper credentials when connecting to
> the linked server - read BOL about sp_addlinkedserver sproc. It is
> possible also that it might be better to join tables on other column[s],
> but you did not give any info on this.
> HTH
> Peter
>|||You have to make sure that they are using the same collation to join
them, sample below:
Select * FROM
sometable localtable
Inner join
SomeotherServer.Database.Owner.SomeTable linkedtable
WHERE linkedserv.Somecolumn COLLATE SQL_Latin1_General_CP1_CI_AI =3D
localtable.somecolumn COLLATE SQL_Latin1_General_CP1_CI_AI
Normally you don=B4t need to specify that on both sides if you just
specify the collation on the side that is different to this on your
local server and vice cersa.
HTH, jens Suessmeyer.|||This means that the two databases use different collations. Look up
collations in Books Online, there you'll also find the COLLATE keyword, whic
h
you can use to solve the problem.
Something like that:
update _customers set flag = 1
from _customers a
inner join Web.ProductCart.dbo.customers b
on a.email = b.email collate <collation
name>
The collation name is displayed in database properties in Enterprise manager
.
ML
http://milambda.blogspot.com/|||Thanks guys, i'll go check it out.
"ML" <ML@.discussions.microsoft.com> wrote in message
news:70933017-66F0-4438-B8EE-E5824B77E3C9@.microsoft.com...
> This means that the two databases use different collations. Look up
> collations in Books Online, there you'll also find the COLLATE keyword,
> which
> you can use to solve the problem.
> Something like that:
> update _customers set flag = 1
> from _customers a
> inner join Web.ProductCart.dbo.customers b
> on a.email = b.email collate <collation
> name>
> The collation name is displayed in database properties in Enterprise
> manager.
>
> ML
> --
> http://milambda.blogspot.com/

Thursday, March 8, 2012

compare and update a table from one database to another table on another databas

Hi everybody.. need help on this situation which i am to.

I have two databases named db1 and db2
both of which has two identical tables named tbl1 and tbl2

I need to compare tbl1 of db1 to the tbl2 of db2
if there is a record that is existing on tbl1 and not on the tbl2 then
i need to create a tblnew on db2
from that tblnew then i need to append all the data from tblnew to tbl2 of db2.

I don't know how to start with it because i'm used to appending data on two tables on the same database but not on a different one...

thanks
alexStart here or read BOL about 4 part naming:

http://mssqltips.com/tip.asp?tip=1095|||Are the databases on the same server? Or Different Server or Instance?

In any case, read this

http://weblogs.sqlteam.com/brettk/archive/2004/04/23/1281.aspx|||on the same server

thanks

Saturday, February 25, 2012

Community Question: Fastest update path for experienced SQL Server 2000 developers.

Hi,
I have several years of experience working on SQL server versions 7-2000.
Now I would like to update my knowledge to SQL Server 2005. The problem is
that most of books I saw try to explain old SQL 2000 features mixed with new
SQL 2005 features.
Could you refer me to books or resources that update my SQL Server knowledge
without bothering with explaining old SQL 2000 related features?
Any help would be appreciated,
MaxHello Maxwell2006,
If you like books, go with http://www.aw-bc.com/catalog/academ...1382188,00.html
(when it comes out)
If you like class room training, come spend a w with me... ;)
Thank you,
Kent Tegels
DevelopMentor
http://staff.develop.com/ktegels/|||Hi Kent,
Thank you for reply.
I am looking for online type of resources and ready to buy books. Do you
know any?
Regards,
Max
"Kent Tegels" <ktegels@.develop.com> wrote in message
news:b87ad74171d48c8144990ba2865@.news.microsoft.com...
> Hello Maxwell2006,
> If you like books, go with
> http://www.aw-bc.com/catalog/academ...1382188,00.html
> (when it comes out)
> If you like class room training, come spend a w with me... ;)
> Thank you,
> Kent Tegels
> DevelopMentor
> http://staff.develop.com/ktegels/
>|||On Sun, 12 Mar 2006 23:57:03 -0500, Maxwell2006 wrote:
(snip)
>Could you refer me to books or resources that update my SQL Server knowledg
e
>without bothering with explaining old SQL 2000 related features?
Hi Max,
I'm in the exact same situation. I've recently (last w) picked up a
copy of "Pro SQL Server 2005" (by Thomas Rizzo et. al.) It does exactly
what you and I want: skip past everything that was already present in
SQL Server 2005 and plunge right into the new features.
First impressions are good, though I should hasten to add that I'm only
halfway chapter 2 yet.
Hugo Kornelis, SQL Server MVP|||Thank you very much Hugo. I was thinking about that book last night and I
wasn't sure I should go ahead or not. Now I am going to order it with
confident.
Thanks again,
Max
"Hugo Kornelis" <hugo@.perFact.REMOVETHIS.info.INVALID> wrote in message
news:fk2c1252kk2b3o28qf2lu5me1dfuemsrs3@.
4ax.com...
> On Sun, 12 Mar 2006 23:57:03 -0500, Maxwell2006 wrote:
> (snip)
> Hi Max,
> I'm in the exact same situation. I've recently (last w) picked up a
> copy of "Pro SQL Server 2005" (by Thomas Rizzo et. al.) It does exactly
> what you and I want: skip past everything that was already present in
> SQL Server 2005 and plunge right into the new features.
> First impressions are good, though I should hasten to add that I'm only
> halfway chapter 2 yet.
> --
> Hugo Kornelis, SQL Server MVP

Friday, February 24, 2012

common UPDATE syntax for SqlServer and Oracle

The UPDATE table FROM syntax is not supported by Oracle.

I am looking for a syntax that is understood by both Oracle and SqlServer.

Example:

Table1:

id name city city_id
1 john newyork null
2 peter london null
3 hans newyork null

Table2:

id city
23 london
24 paris
25 newyork

UPDATE table1
SET city_id = table2.id
FROM table1, table2
WHERE table1.city = Table2.city

If possible I do not want to have two different statements for Oracle and
SqlServer

Please do not tell me that these tables are not normalized, it's just an
example!

Thanks for any hints.

Jan van VeldhuizenThe ANSI Standard syntax supported by both products is

UPDATE Table1
SET city_id =
(SELECT T2.id
FROM Table2 AS T2
WHERE T2.city = Table1.city) ;

Depending on requirements you may want to include a WHERE EXISTS (equivalent
to the proprietary INNER JOIN syntax)

UPDATE Table1
SET city_id =
(SELECT T2.id
FROM Table2 AS T2
WHERE T2.city = Table1.city)
WHERE EXISTS
(SELECT *
FROM Table2 AS T2
WHERE T2.city = Table1.city) ;

--
David Portas
SQL Server MVP
--|||Like most new ideas, the hard part of understanding what the relational
model is comes in un-learning what you know about file systems. As
Artemus Ward (William Graham Sumner, 1840-1910) put it, "It ain't so
much the things we don't know that get us into trouble. It's the things
we know that just ain't so."

If you already have a background in data processing with traditional
file systems, the first things to un-learn are:

(0) Databases are not file sets.
(1) Tables are not files.
(2) Rows are not records.
(3) Columns are not fields.

Modern data processing began with punch cards, or Hollerith cards used
by the Bureau of the Census. Their original size was that of a United
States Dollar bill. This was set by their inventor, Herman Hollerith,
because he could get furniture to store the cards from the United States
Treasury Department, just across the street. Likewise, physical
constraints limited each card to 80 columns of holes in which to record
a symbol.

The influence of the punch card lingered on long after the invention of
magnetic tapes and disk for data storage. This is why early video
display terminals were 80 columns across. Even today, files which were
migrated from cards to magnetic tape files or disk storage still use 80
column records.

But the influence was not just on the physical side of data processing.
The methods for handling data from the prior media were imitated in the
new media.

Data processing first consisted of sorting and merging decks of punch
cards (later, sequential magnetic tape files) in a series of distinct
steps. The result of each step feed into the next step in the process.

Relational databases do not work that way. Each user connects to the
entire database all at once, not to one file at time in a sequence of
steps. The users might not all have the same database access rights
once they are connected, however. Magnetic tapes could not be shared
among users at the same time, but shared data is the point of a
database.

Tables versus Files

A file is closely related to its physical storage media. A table may or
may not be a physical file. DB2 from IBM uses one file per table,
while Sybase puts several entire databases inside one file. A table is
a <i>set<i> of rows of the same kind of thing. A set has no ordering
and it makes no sense to ask for the first or last row.

A deck of punch cards is sequential, and so are magnetic tape files.
Therefore, a <i>physical<i> file of ordered sequential records also
became the <i>mental<i> model for data processing and it is still hard
to shake. Anytime you look at data, it is in some physical ordering.

The various access methods for disk storage system came later, but even
these access methods could not shake the mental model.

Another conceptual difference is that a file is usually data that deals
with a whole business process. A file has to have enough data in
itself to support applications for that business process. Files tend to
be "mixed" data which can be described by the name of the business
process, such as "The Payroll file" or something like that.

Tables can be either entities or relationships within a business
process. This means that the data which was held in one file is often
put into several tables. Tables tend to be "pure" data which can be
described by single words. The payroll would now have separate tables
for timecards, employees, projects and so forth.

Tables as Entities

An entity is physical or conceptual "thing" which has meaning be itself.
A person, a sale or a product would be an example. In a relational
database, an entity is defined by its attributes, which are shown as
values in columns in rows in a table.

To remind users that tables are sets of entities, I like to use plural
or collective nouns that describe the function of the entities within
the system for the names of tables. Thus "Employee" is a bad name
because it is singular; "Employees" is a better name because it is
plural; "Personnel" is best because it is collective and does not summon
up a mental picture of individual persons.

If you have tables with exactly the same structure, then they are sets
of the same kind of elements. But you should have only one set for each
kind of data element! Files, on the other hand, were PHYSICALLY
separate units of storage which coudl be alike -- each tape or disk file
represents a step in the PROCEDURE , such as moving from raw data, to
edited data, and finally to archived data. In SQL, this should be a
status flag in a table.

Tables as Relationships

A relationship is shown in a table by columns which reference one or
more entity tables. Without the entities, the relationship has no
meaning, but the relationship can have attributes of its own. For
example, a show business contract might have an agent, an employer and
a talent. The method of payment is an attribute of the contract itself,
and not of any of the three parties.

Rows versus Records

Rows are not records. A record is defined in the application program
which reads it; a row is defined in the database schema and not by a
program at all. The name of the field in the READ or INPUT statements
of the application; a row is named in the database schema.

All empty files look alike; they are a directory entry in the operating
system with a name and a length of zero bytes of storage. Empty tables
still have columns, constraints, security privileges and other
structures, even tho they have no rows.

This is in keeping with the set theoretical model, in which the empty
set is a perfectly good set. The difference between SQL's set model and
standard mathematical set theory is that set theory has only one empty
set, but in SQL each table has a different structure, so they cannot be
used in places where non-empty versions of themselves could not be used.

Another characteristic of rows in a table is that they are all alike in
structure and they are all the "same kind of thing" in the model. In a
file system, records can vary in size, datatypes and structure by having
flags in the data stream that tell the program reading the data how to
interpret it. The most common examples are Pascal's variant record, C's
struct syntax and Cobol's OCCURS clause.

The OCCURS keyword in Cobol and the Variant records in Pascal have a
number which tells the program how many time a record structure is to be
repeated in the current record.

Unions in 'C' are not variant records, but variant mappings for the same
physical memory. For example:

union x {int ival; char j[4];} myStuff;

defines myStuff to be either an integer (which are 4 bytes on most
modern C compilers, but this code is non-portable) or an array of 4
bytes, depending on whether you say myStuff.ival or myStuff.j[0];

But even more than that, files often contained records which were
summaries of subsets of the other records -- so called control break
reports. There is no requirement that the records in a file be related
in any way -- they are literally a stream of binary data whose meaning
is assigned by the program reading them.

Columns versus Fields

A field within a record is defined by the application program that reads
it. A column in a row in a table is defined by the database schema.
The datatypes in a column are always scalar.

The order of the application program variables in the READ or INPUT
statements is important because the values are read into the program
variables in that order. In SQL, columns are referenced only by their
names. Yes, there are shorthands like the SELECT * clause and INSERT
INTO <table name> statements which expand into a list of column names in
the physical order in which the column names appear within their table
declaration, but these are shorthands which resolve to named lists.

The use of NULLs in SQL is also unique to the language. Fields do not
support a missing data marker as part of the field, record or file
itself. Nor do fields have constraints which can be added to them in
the record, like the DEFAULT and CHECK() clauses in SQL.

Relationships among tables within a database

Files are pretty passive creatures and will take whatever an application
program throws at them without much objection. Files are also
independent of each other simply because they are connected to one
application program at a time and therefore have no idea what other
files looks like.

A database actively seeks to maintain the correctness of all its data.
The methods used are triggers, constraints and declarative referential
integrity.

Declarative referential integrity (DRI) says, in effect, that data in
one table has a particular relationship with data in a second (possibly
the same) table. It is also possible to have the database change
itself via referential actions associated with the DRI.

For example, a business rule might be that we do not sell products which
are not in inventory. This rule would be enforce by a REFERENCES clause
on the Orders table which references the Inventory table and a
referential action of ON DELETE CASCADE

Triggers are a more general way of doing much the same thing as DRI. A
trigger is a block of procedural code which is executed before, after or
instead of an INSERT INTO or UPDATE statement. You can do anything with
a trigger that you can do with DRI and more.

However, there are problems with TRIGGERs. While there is a standard
syntax for them in the SQL-92 standard, most vendors have not
implemented it. What they have is very proprietary syntax instead.
Secondly, a trigger cannot pass information to the optimizer like DRI.
In the example in this section, I know that for every product number in
the Orders table, I have that same product number in the Inventory
table. The optimizer can use that information in setting up EXISTS()
predicates and JOINs in the queries. There is no reasonable way to
parse procedural trigger code to determine this relationship.

The CREATE ASSERTION statement in SQL-92 will allow the database to
enforce conditions on the entire database as a whole. An ASSERTION is
not like a CHECK() clause, but the difference is subtle. A CHECK()
clause is executed when there are rows in the table to which it is
attached. If the table is empty then all CHECK() clauses are
effectively TRUE. Thus, if we wanted to be sure that the Inventory
table is never empty, and we wrote:

CREATE TABLE Inventory
( ...
CONSTRAINT inventory_not_empty
CHECK ((SELECT COUNT(*) FROM Inventory) > 0), ... );

it would not work. However, we could write:

CREATE ASSERTION Inventory_not_empty
CHECK ((SELECT COUNT(*) FROM Inventory) > 0);

and we would get the desired results. The assertion is checked at the
schema level and not at the table level.

--CELKO--
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Sample data is also a good idea, along with clear
specifications.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!|||Thanks. I'm going to test that.

That syntax will work with one column to be updated.
What if I have to columns?

I think the oracle sql will support something like:
UPDATE Table1
SET (city_id, another_column) =
(SELECT T2.id, other_column FROM etctera...

But that no standard SqlServer syntax as far as I know.

"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:qoednbGWLZwC-TvcRVn-1A@.giganews.com...
> The ANSI Standard syntax supported by both products is
> UPDATE Table1
> SET city_id =
> (SELECT T2.id
> FROM Table2 AS T2
> WHERE T2.city = Table1.city) ;
> Depending on requirements you may want to include a WHERE EXISTS
> (equivalent to the proprietary INNER JOIN syntax)
> UPDATE Table1
> SET city_id =
> (SELECT T2.id
> FROM Table2 AS T2
> WHERE T2.city = Table1.city)
> WHERE EXISTS
> (SELECT *
> FROM Table2 AS T2
> WHERE T2.city = Table1.city) ;
> --
> David Portas
> SQL Server MVP
> --|||On Fri, 26 Nov 2004 11:01:39 +0100, Jan van Veldhuizen wrote:

>Thanks. I'm going to test that.
>That syntax will work with one column to be updated.
>What if I have to columns?
>I think the oracle sql will support something like:
>UPDATE Table1
> SET (city_id, another_column) =
> (SELECT T2.id, other_column FROM etctera...
>But that no standard SqlServer syntax as far as I know.

Hi Jan,

That's right. Using ANSI-standard SQL, the only way to update multiple
columns with values from another table is to repeat the subquery:

UPDATE Table1
SET city_id = (SELECT T2.id FROM etcetera...)
, another_column = (SELECT other_column FROM etcetera...)
WHERE ...

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hugo Kornelis wrote:
> On Fri, 26 Nov 2004 11:01:39 +0100, Jan van Veldhuizen wrote:
>
>>Thanks. I'm going to test that.
>>
>>That syntax will work with one column to be updated.
>>What if I have to columns?
>>
>>I think the oracle sql will support something like:
>>UPDATE Table1
>> SET (city_id, another_column) =
>> (SELECT T2.id, other_column FROM etctera...
>>
>>But that no standard SqlServer syntax as far as I know.
>
> Hi Jan,
> That's right. Using ANSI-standard SQL, the only way to update multiple
> columns with values from another table is to repeat the subquery:
> UPDATE Table1
> SET city_id = (SELECT T2.id FROM etcetera...)
> , another_column = (SELECT other_column FROM etcetera...)
> WHERE ...
> Best, Hugo
I believe the ANSI standard allows:
UPDATE Table1
SET (city_id, another_column) = (SELECT T2.id, other column FROM etc
WHERE ...)
WHERE EXISTS(...)

Cheers
Serge|||On Fri, 26 Nov 2004 07:31:59 -0500, Serge Rielau wrote:

>I believe the ANSI standard allows:
>UPDATE Table1
> SET (city_id, another_column) = (SELECT T2.id, other column FROM etc
>WHERE ...)
>WHERE EXISTS(...)

Hi Serge,

Umm, yes. I believe you're right. Unfortunately, that part of ANSI sql is
not available in SQL Server 2000 (don't know about Oracle, thoug), so it
won't help Jan.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)|||"Jan van Veldhuizen" <jan@.van-veldhuizen.nl> wrote in message news:<41a6fed9$0$78279$e4fe514c@.news.xs4all.nl>...
> Thanks. I'm going to test that.
> That syntax will work with one column to be updated.
> What if I have to columns?
> I think the oracle sql will support something like:
> UPDATE Table1
> SET (city_id, another_column) =
> (SELECT T2.id, other_column FROM etctera...
> But that no standard SqlServer syntax as far as I know.

Jan,

The multi-column UPDATE you describe above is actually included in the
SQL-2003 standard. (The non-Core feauture T641 - "Multiple column
assignment")

Regards,
Jarl|||Hugo Kornelis wrote:
> On Fri, 26 Nov 2004 07:31:59 -0500, Serge Rielau wrote:
>
>>I believe the ANSI standard allows:
>>UPDATE Table1
>> SET (city_id, another_column) = (SELECT T2.id, other column FROM etc
>>WHERE ...)
>>WHERE EXISTS(...)
>
> Hi Serge,
> Umm, yes. I believe you're right. Unfortunately, that part of ANSI sql is
> not available in SQL Server 2000 (don't know about Oracle, thoug), so it
> won't help Jan.
> Best, Hugo

It does exist in Oracle. Too bad about SQL Server though.
--
Daniel A. Morgan
University of Washington
damorgan@.x.washington.edu
(replace 'x' with 'u' to respond)

Sunday, February 19, 2012

Commit, select or update duration time vary from short to long

Hi
I have a statement that normally takes a short time but sometimes
takes long. I think I have isolated the problem to being variations in
the time it takes to commit.
I have constructed a setup that somehow show my problem.
First execute the following script (45 lines):
use pubs
/****** Object: Stored Procedure dbo.spTestCommit Script Date:
16-05-2005 08:20:27 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].
[spTestCommit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spTestCommit]
GO
/****** Object: StoredProcedure [dbo].[spTestCommit] Script Date
:
05/16/2007 08:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spTestCommit]
@.deltaValue int,
@.titleId varchar(50)
AS
declare @.tranCount int
select @.tranCount = @.@.trancount
if (@.tranCount = 0) begin
tran spTran
else begin
save tran spTran
end
UPDATE titles
SET ytd_sales = ytd_sales + @.deltaValue
WHERE title_id = @.titleId
if (@.tranCount = 0)
begin
commit tran
end
return 0
errorHandler:
rollback tran spTran
return 1
GO
Then start a trace enabling Execution plan and execute the statement.
I use the following:
exec spTestCommit 1, 'BU1032'
exec spTestCommit -1, 'BU1032'
(This will decrease and then increase some int value in the
pubs..titles table for a specific record)
Now my point is that when I execute those 2 lines, then they have a
duration of 10 or 20 ms most of the time. But all of the sudden I see
an entry with a duration of 210 ms.
Why does it take so much longer when that is the only thing I execute
on that entire database?!?
The output from my trace for the 210 ms run is:
Execution Plan Execution Tree
--
Clustered Index Update(OBJECT[pubs].[dbo].[titles].
[UPKCL_titleidind]), SET[titles].[ytd_sales]=[Expr1004]),
DEFINE:
([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE[
;titles].
[title_id]=[@.titleId]))
SQL Query Analyzer usr PC\usr 2756 55 2007-05-16 13:11:23.553
Execution Plan Execution Tree
--
Clustered Index Update(OBJECT[pubs].[dbo].[titles].
[UPKCL_titleidind]), SET[titles].[ytd_sales]=[Expr1004]),
DEFINE:
([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE[
;titles].
[title_id]=[@.titleId]))
SQL Query Analyzer usr PC\usr 2756 55 2007-05-16 13:11:23.703
SQL:BatchCompleted exec spTestCommit 1, 'BU1032'
exec spTestCommit -1, 'BU1032'
SQL Query Analyzer usr PC\usr 0 18 0 210 2756 55 2
007-05-16
13:11:23.553 2007-05-16 13:11:23.763
In my real world setup I have a stored procedure that normally takes
0-20 ms but have been seen taking 30000 ms or even more... I would
very much apreciate some hints as to why it vary so much...
Thanks
Resist> Now my point is that when I execute those 2 lines, then they have a
> duration of 10 or 20 ms most of the time. But all of the sudden I see
> an entry with a duration of 210 ms.
> Why does it take so much longer when that is the only thing I execute
> on that entire database?!?
SQL Server must wait until the COMMIT log write is physically complete
before completing the statement. If a CHECKPOINT is writing lots of data
and data and log files are on the same physical disk, this can prolong the
COMMIT statement duration. This is one reason why it's a Best Practice to
place data and log on different disks. You can monitor checkpoints in
perfmon to see the correlation.

> In my real world setup I have a stored procedure that normally takes
> 0-20 ms but have been seen taking 30000 ms or even more... I would
> very much apreciate some hints as to why it vary so much...
30+ seconds is excessive and probably due to a different reason, assuming
your I/O subsystem is adequately sized for your workload. A more likely
cause is blocking. Run sp_who at the time of the problem to see if that's
the case. An occasional long-running query or transaction may be the
culprit.
Hope this helps.
Dan Guzman
SQL Server MVP
"resist" <dba@.godhund.dk> wrote in message
news:1179315894.009631.298820@.y80g2000hsf.googlegroups.com...
> Hi
> I have a statement that normally takes a short time but sometimes
> takes long. I think I have isolated the problem to being variations in
> the time it takes to commit.
> I have constructed a setup that somehow show my problem.
> First execute the following script (45 lines):
> use pubs
> /****** Object: Stored Procedure dbo.spTestCommit Script Date:
> 16-05-2005 08:20:27 ******/
> if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].
> [spTestCommit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
> drop procedure [dbo].[spTestCommit]
> GO
> /****** Object: StoredProcedure [dbo].[spTestCommit] Script Da
te:
> 05/16/2007 08:32:43 ******/
> SET ANSI_NULLS ON
> GO
> SET QUOTED_IDENTIFIER ON
> GO
> CREATE PROCEDURE [dbo].[spTestCommit]
> @.deltaValue int,
> @.titleId varchar(50)
>
> AS
> declare @.tranCount int
> select @.tranCount = @.@.trancount
> if (@.tranCount = 0) begin
> tran spTran
> else begin
> save tran spTran
> end
> UPDATE titles
> SET ytd_sales = ytd_sales + @.deltaValue
> WHERE title_id = @.titleId
>
> if (@.tranCount = 0)
> begin
> commit tran
> end
> return 0
> errorHandler:
> rollback tran spTran
> return 1
> GO
>
>
> Then start a trace enabling Execution plan and execute the statement.
> I use the following:
> exec spTestCommit 1, 'BU1032'
> exec spTestCommit -1, 'BU1032'
> (This will decrease and then increase some int value in the
> pubs..titles table for a specific record)
>
> Now my point is that when I execute those 2 lines, then they have a
> duration of 10 or 20 ms most of the time. But all of the sudden I see
> an entry with a duration of 210 ms.
> Why does it take so much longer when that is the only thing I execute
> on that entire database?!?
> The output from my trace for the 210 ms run is:
> Execution Plan Execution Tree
> --
> Clustered Index Update(OBJECT[pubs].[dbo].[titles].
> [UPKCL_titleidind]), SET[titles].[ytd_sales]=[Expr1004])
, DEFINE:
> ([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE&#
91;titles].
> [title_id]=[@.titleId]))
> SQL Query Analyzer usr PC\usr 2756 55 2007-05-16 13:11:23.553
> Execution Plan Execution Tree
> --
> Clustered Index Update(OBJECT[pubs].[dbo].[titles].
> [UPKCL_titleidind]), SET[titles].[ytd_sales]=[Expr1004])
, DEFINE:
> ([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE&#
91;titles].
> [title_id]=[@.titleId]))
> SQL Query Analyzer usr PC\usr 2756 55 2007-05-16 13:11:23.703
> SQL:BatchCompleted exec spTestCommit 1, 'BU1032'
> exec spTestCommit -1, 'BU1032'
> SQL Query Analyzer usr PC\usr 0 18 0 210 2756 55 2007-05-16
> 13:11:23.553 2007-05-16 13:11:23.763
>
> In my real world setup I have a stored procedure that normally takes
> 0-20 ms but have been seen taking 30000 ms or even more... I would
> very much apreciate some hints as to why it vary so much...
> Thanks
> Resist
>

Commit, select or update duration time vary from short to long

Hi
I have a statement that normally takes a short time but sometimes
takes long. I think I have isolated the problem to being variations in
the time it takes to commit.
I have constructed a setup that somehow show my problem.
First execute the following script (45 lines):
use pubs
/****** Object: Stored Procedure dbo.spTestCommit Script Date:
16-05-2005 08:20:27 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].
[spTestCommit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spTestCommit]
GO
/****** Object: StoredProcedure [dbo].[spTestCommit] Script Date:
05/16/2007 08:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spTestCommit]
@.deltaValue int,
@.titleId varchar(50)
AS
declare @.tranCount int
select @.tranCount = @.@.trancount
if (@.tranCount = 0) begin
tran spTran
else begin
save tran spTran
end
UPDATE titles
SET ytd_sales = ytd_sales + @.deltaValue
WHERE title_id = @.titleId
if (@.tranCount = 0)
begin
commit tran
end
return 0
errorHandler:
rollback tran spTran
return 1
GO
Then start a trace enabling Execution plan and execute the statement.
I use the following:
exec spTestCommit 1, 'BU1032'
exec spTestCommit -1, 'BU1032'
(This will decrease and then increase some int value in the
pubs..titles table for a specific record)
Now my point is that when I execute those 2 lines, then they have a
duration of 10 or 20 ms most of the time. But all of the sudden I see
an entry with a duration of 210 ms.
Why does it take so much longer when that is the only thing I execute
on that entire database?!?
The output from my trace for the 210 ms run is:
Execution PlanExecution Tree
Clustered Index Update(OBJECT[pubs].[dbo].[titles].
[UPKCL_titleidind]), SET[titles].[ytd_sales]=[Expr1004]), DEFINE:
([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE[titles].
[title_id]=[@.titleId]))
SQL Query AnalyzerusrPC\usr2756552007-05-16 13:11:23.553
Execution PlanExecution Tree
Clustered Index Update(OBJECT[pubs].[dbo].[titles].
[UPKCL_titleidind]), SET[titles].[ytd_sales]=[Expr1004]), DEFINE:
([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE[titles].
[title_id]=[@.titleId]))
SQL Query AnalyzerusrPC\usr2756552007-05-16 13:11:23.703
SQL:BatchCompletedexec spTestCommit 1, 'BU1032'
exec spTestCommit -1, 'BU1032'
SQL Query AnalyzerusrPC\usr01802102756552007-05-16
13:11:23.5532007-05-16 13:11:23.763
In my real world setup I have a stored procedure that normally takes
0-20 ms but have been seen taking 30000 ms or even more... I would
very much apreciate some hints as to why it vary so much...
Thanks
Resist
> Now my point is that when I execute those 2 lines, then they have a
> duration of 10 or 20 ms most of the time. But all of the sudden I see
> an entry with a duration of 210 ms.
> Why does it take so much longer when that is the only thing I execute
> on that entire database?!?
SQL Server must wait until the COMMIT log write is physically complete
before completing the statement. If a CHECKPOINT is writing lots of data
and data and log files are on the same physical disk, this can prolong the
COMMIT statement duration. This is one reason why it's a Best Practice to
place data and log on different disks. You can monitor checkpoints in
perfmon to see the correlation.

> In my real world setup I have a stored procedure that normally takes
> 0-20 ms but have been seen taking 30000 ms or even more... I would
> very much apreciate some hints as to why it vary so much...
30+ seconds is excessive and probably due to a different reason, assuming
your I/O subsystem is adequately sized for your workload. A more likely
cause is blocking. Run sp_who at the time of the problem to see if that's
the case. An occasional long-running query or transaction may be the
culprit.
Hope this helps.
Dan Guzman
SQL Server MVP
"resist" <dba@.godhund.dk> wrote in message
news:1179315894.009631.298820@.y80g2000hsf.googlegr oups.com...
> Hi
> I have a statement that normally takes a short time but sometimes
> takes long. I think I have isolated the problem to being variations in
> the time it takes to commit.
> I have constructed a setup that somehow show my problem.
> First execute the following script (45 lines):
> use pubs
> /****** Object: Stored Procedure dbo.spTestCommit Script Date:
> 16-05-2005 08:20:27 ******/
> if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].
> [spTestCommit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
> drop procedure [dbo].[spTestCommit]
> GO
> /****** Object: StoredProcedure [dbo].[spTestCommit] Script Date:
> 05/16/2007 08:32:43 ******/
> SET ANSI_NULLS ON
> GO
> SET QUOTED_IDENTIFIER ON
> GO
> CREATE PROCEDURE [dbo].[spTestCommit]
> @.deltaValue int,
> @.titleId varchar(50)
>
> AS
> declare @.tranCount int
> select @.tranCount = @.@.trancount
> if (@.tranCount = 0) begin
> tran spTran
> else begin
> save tran spTran
> end
> UPDATE titles
> SET ytd_sales = ytd_sales + @.deltaValue
> WHERE title_id = @.titleId
>
> if (@.tranCount = 0)
> begin
> commit tran
> end
> return 0
> errorHandler:
> rollback tran spTran
> return 1
> GO
>
>
> Then start a trace enabling Execution plan and execute the statement.
> I use the following:
> exec spTestCommit 1, 'BU1032'
> exec spTestCommit -1, 'BU1032'
> (This will decrease and then increase some int value in the
> pubs..titles table for a specific record)
>
> Now my point is that when I execute those 2 lines, then they have a
> duration of 10 or 20 ms most of the time. But all of the sudden I see
> an entry with a duration of 210 ms.
> Why does it take so much longer when that is the only thing I execute
> on that entire database?!?
> The output from my trace for the 210 ms run is:
> Execution Plan Execution Tree
> --
> Clustered Index Update(OBJECT[pubs].[dbo].[titles].
> [UPKCL_titleidind]), SET[titles].[ytd_sales]=[Expr1004]), DEFINE:
> ([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE[titles].
> [title_id]=[@.titleId]))
> SQL Query Analyzer usr PC\usr 2756 55 2007-05-16 13:11:23.553
> Execution Plan Execution Tree
> --
> Clustered Index Update(OBJECT[pubs].[dbo].[titles].
> [UPKCL_titleidind]), SET[titles].[ytd_sales]=[Expr1004]), DEFINE:
> ([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE[titles].
> [title_id]=[@.titleId]))
> SQL Query Analyzer usr PC\usr 2756 55 2007-05-16 13:11:23.703
> SQL:BatchCompleted exec spTestCommit 1, 'BU1032'
> exec spTestCommit -1, 'BU1032'
> SQL Query Analyzer usr PC\usr 0 18 0 210 2756 55 2007-05-16
> 13:11:23.553 2007-05-16 13:11:23.763
>
> In my real world setup I have a stored procedure that normally takes
> 0-20 ms but have been seen taking 30000 ms or even more... I would
> very much apreciate some hints as to why it vary so much...
> Thanks
> Resist
>

Commit, select or update duration time vary from short to long

Hi
I have a statement that normally takes a short time but sometimes
takes long. I think I have isolated the problem to being variations in
the time it takes to commit.
I have constructed a setup that somehow show my problem.
First execute the following script (45 lines):
use pubs
/****** Object: Stored Procedure dbo.spTestCommit Script Date:
16-05-2005 08:20:27 ******/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].
[spTestCommit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spTestCommit]
GO
/****** Object: StoredProcedure [dbo].[spTestCommit] Script Date:
05/16/2007 08:32:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spTestCommit]
@.deltaValue int,
@.titleId varchar(50)
AS
declare @.tranCount int
select @.tranCount = @.@.trancount
if (@.tranCount = 0) begin
tran spTran
else begin
save tran spTran
end
UPDATE titles
SET ytd_sales = ytd_sales + @.deltaValue
WHERE title_id = @.titleId
if (@.tranCount = 0)
begin
commit tran
end
return 0
errorHandler:
rollback tran spTran
return 1
GO
Then start a trace enabling Execution plan and execute the statement.
I use the following:
exec spTestCommit 1, 'BU1032'
exec spTestCommit -1, 'BU1032'
(This will decrease and then increase some int value in the
pubs..titles table for a specific record)
Now my point is that when I execute those 2 lines, then they have a
duration of 10 or 20 ms most of the time. But all of the sudden I see
an entry with a duration of 210 ms.
Why does it take so much longer when that is the only thing I execute
on that entire database?!?
The output from my trace for the 210 ms run is:
Execution Plan Execution Tree
--
Clustered Index Update(OBJECT:([pubs].[dbo].[titles].
[UPKCL_titleidind]), SET:([titles].[ytd_sales]=[Expr1004]), DEFINE:
([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE:([titles].
[title_id]=[@.titleId]))
SQL Query Analyzer usr PC\usr 2756 55 2007-05-16 13:11:23.553
Execution Plan Execution Tree
--
Clustered Index Update(OBJECT:([pubs].[dbo].[titles].
[UPKCL_titleidind]), SET:([titles].[ytd_sales]=[Expr1004]), DEFINE:
([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE:([titles].
[title_id]=[@.titleId]))
SQL Query Analyzer usr PC\usr 2756 55 2007-05-16 13:11:23.703
SQL:BatchCompleted exec spTestCommit 1, 'BU1032'
exec spTestCommit -1, 'BU1032'
SQL Query Analyzer usr PC\usr 0 18 0 210 2756 55 2007-05-16
13:11:23.553 2007-05-16 13:11:23.763
In my real world setup I have a stored procedure that normally takes
0-20 ms but have been seen taking 30000 ms or even more... I would
very much apreciate some hints as to why it vary so much...
Thanks
Resist> Now my point is that when I execute those 2 lines, then they have a
> duration of 10 or 20 ms most of the time. But all of the sudden I see
> an entry with a duration of 210 ms.
> Why does it take so much longer when that is the only thing I execute
> on that entire database?!?
SQL Server must wait until the COMMIT log write is physically complete
before completing the statement. If a CHECKPOINT is writing lots of data
and data and log files are on the same physical disk, this can prolong the
COMMIT statement duration. This is one reason why it's a Best Practice to
place data and log on different disks. You can monitor checkpoints in
perfmon to see the correlation.
> In my real world setup I have a stored procedure that normally takes
> 0-20 ms but have been seen taking 30000 ms or even more... I would
> very much apreciate some hints as to why it vary so much...
30+ seconds is excessive and probably due to a different reason, assuming
your I/O subsystem is adequately sized for your workload. A more likely
cause is blocking. Run sp_who at the time of the problem to see if that's
the case. An occasional long-running query or transaction may be the
culprit.
--
Hope this helps.
Dan Guzman
SQL Server MVP
"resist" <dba@.godhund.dk> wrote in message
news:1179315894.009631.298820@.y80g2000hsf.googlegroups.com...
> Hi
> I have a statement that normally takes a short time but sometimes
> takes long. I think I have isolated the problem to being variations in
> the time it takes to commit.
> I have constructed a setup that somehow show my problem.
> First execute the following script (45 lines):
> use pubs
> /****** Object: Stored Procedure dbo.spTestCommit Script Date:
> 16-05-2005 08:20:27 ******/
> if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].
> [spTestCommit]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
> drop procedure [dbo].[spTestCommit]
> GO
> /****** Object: StoredProcedure [dbo].[spTestCommit] Script Date:
> 05/16/2007 08:32:43 ******/
> SET ANSI_NULLS ON
> GO
> SET QUOTED_IDENTIFIER ON
> GO
> CREATE PROCEDURE [dbo].[spTestCommit]
> @.deltaValue int,
> @.titleId varchar(50)
>
> AS
> declare @.tranCount int
> select @.tranCount = @.@.trancount
> if (@.tranCount = 0) begin
> tran spTran
> else begin
> save tran spTran
> end
> UPDATE titles
> SET ytd_sales = ytd_sales + @.deltaValue
> WHERE title_id = @.titleId
>
> if (@.tranCount = 0)
> begin
> commit tran
> end
> return 0
> errorHandler:
> rollback tran spTran
> return 1
> GO
>
>
> Then start a trace enabling Execution plan and execute the statement.
> I use the following:
> exec spTestCommit 1, 'BU1032'
> exec spTestCommit -1, 'BU1032'
> (This will decrease and then increase some int value in the
> pubs..titles table for a specific record)
>
> Now my point is that when I execute those 2 lines, then they have a
> duration of 10 or 20 ms most of the time. But all of the sudden I see
> an entry with a duration of 210 ms.
> Why does it take so much longer when that is the only thing I execute
> on that entire database?!?
> The output from my trace for the 210 ms run is:
> Execution Plan Execution Tree
> --
> Clustered Index Update(OBJECT:([pubs].[dbo].[titles].
> [UPKCL_titleidind]), SET:([titles].[ytd_sales]=[Expr1004]), DEFINE:
> ([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE:([titles].
> [title_id]=[@.titleId]))
> SQL Query Analyzer usr PC\usr 2756 55 2007-05-16 13:11:23.553
> Execution Plan Execution Tree
> --
> Clustered Index Update(OBJECT:([pubs].[dbo].[titles].
> [UPKCL_titleidind]), SET:([titles].[ytd_sales]=[Expr1004]), DEFINE:
> ([Expr1004]=[titles].[ytd_sales]+[@.deltaValue]), WHERE:([titles].
> [title_id]=[@.titleId]))
> SQL Query Analyzer usr PC\usr 2756 55 2007-05-16 13:11:23.703
> SQL:BatchCompleted exec spTestCommit 1, 'BU1032'
> exec spTestCommit -1, 'BU1032'
> SQL Query Analyzer usr PC\usr 0 18 0 210 2756 55 2007-05-16
> 13:11:23.553 2007-05-16 13:11:23.763
>
> In my real world setup I have a stored procedure that normally takes
> 0-20 ms but have been seen taking 30000 ms or even more... I would
> very much apreciate some hints as to why it vary so much...
> Thanks
> Resist
>

Commit Update to SQL Database Table

The following code will not update and commit the update to a SQL Database Table. Now my where statement is looking for a Date field. Could this be the problem?

Dim DBConnAs SqlConnection

Dim DBAddAsNew SqlCommand

Dim strConnectAsString = ConfigurationManager.ConnectionStrings("ProtoCostConnectionString").ConnectionString

DBConn =New SqlConnection(strConnect)

'Update a existing row in the table

DBAdd.CommandText ="UPDATE [D12_MIS] SET [CSJ] = @.CSJ, [EST_DATE] = @.EST_DATE, [RECORD_LOCK_FLAG] = @.RECORD_LOCK_FLAG, [EST_CREATE_BY_NAME] = @.EST_CREATE_BY_NAME, [EST_REVIEW_BY_NAME] = @.EST_REVIEW_BY_NAME, [m2_1] = @.m2_1, [m2_2_date] = @.m2_2_date, [m2_3_date] = @.m2_3_date, [m2_4_date] = @.m2_4_date, [m2_5] = @.m2_5, [m3_1a] = @.m3_1a, [m3_1b] = @.m3_1b, [m3_2a] = @.m3_2a, [m3_2b] = @.m3_2b, [m3_3a] = @.m3_3a, [m3_3b] = @.m3_3b WHERE [EST_DATE] = " & EstDateText

With DBAdd.Parameters

.AddWithValue("@.CSJ", pvCSJ.Text)

.AddWithValue("@.EST_DATE", tmp1Date)

.AddWithValue("@.RECORD_LOCK_FLAG", tmpRecordLock)

.AddWithValue("@.EST_CREATE_BY_NAME", CheckedCreator)

.AddWithValue("@.EST_REVIEW_BY_NAME", CheckedReviewer)

.AddWithValue("@.m2_1", vb2_1)

.AddWithValue("@.m2_2_date", tmp2Date)

.AddWithValue("@.m2_3_date", tmp3Date)

.AddWithValue("@.m2_4_date", tmp4Date)

.AddWithValue("@.m2_5", vb2_5)

.AddWithValue("@.m3_1a", vb3_1a)

.AddWithValue("@.m3_1b", vb3_1b)

.AddWithValue("@.m3_2a", vb3_2a)

.AddWithValue("@.m3_2b", vb3_2b)

.AddWithValue("@.m3_3a", vb3_3a)

.AddWithValue("@.m3_3b", vb3_3b)

EndWith

DBAdd.Connection = DBConn

DBAdd.Connection.Open()

Dim rowsAffectedAsInteger = 0

Try

rowsAffected = DBAdd.ExecuteNonQuery

Catch exAs Exception

tb2_2.Text = ex.ToString()

Finally

DBAdd.Connection.Close()

EndTry

tb2_1.Text = rowsAffected

Yes. Since a date column (datetime) consists of both date and time portion, you WHERE clause will attempt to match both the date and the time values. Chances are, you don't have the time portion specified (or a different one), so nothing will be matched. Instead, try to use the format:

WHERE [EST_DATE] >= '02/18/2006 12:00:00 AM' AND [EST_DATE] <= '02/18/2006 11:59:59 PM'

or

WHERE [EST_DATE] >= '02/18/2006' AND [EST_DATE]< '02/19/2006'

Notice that when yo specify only the date portion, the time portion defaults to 12:00:00 AM, so the second method uses less-than (<) the following date of the date you're trying to filter.|||

WHERE [EST_DATE] = " & EstDateText .

I think the problem is that you have not enclosed the date with single quotes. Try the following one

WHERE [EST_DATE] = '" & EstDateText & "'"

|||That was the problem of missing quotes, thanks!|||Change the date to a parameter, and you wouldn't have had that problem.

commit after 10000 rows

Hi
I need to update a vary large amount of records (3 million). I don't want to wait till the end of the update to commit.
do you know how can I commit the transaction after, lets say 10000 rows, and then continue to the next 10000... and so on ?
I think it's one of the SET commands but I can't remember it.set rowcount 10000

while (still have records to be updated)
begin
update records
end

set rowcount 0

Originally posted by aig
Hi
I need to update a vary large amount of records (3 million). I don't want to wait till the end of the update to commit.
do you know how can I commit the transaction after, lets say 10000 rows, and then continue to the next 10000... and so on ?
I think it's one of the SET commands but I can't remember it.

Thursday, February 16, 2012

comment

I am trying to update a field called NodeName from [Table A] to add the
characters "?BadLink" to the end of the NodeName based on NodeID being equal
to [Table B].NodeName. How can I do this?
Example
TableA.NodeID=12345 and TableB.NodeID=12345
update the nodename "NameoftheNode" in table A to be "NameoftheNode?BadLink"Update TableA
set NodeName=NodeName + '?BadLink'
where NodeID in
(select NodeID from TableB
where NodeID=12345 --use this line if you want to update one row at a time
)
or
Update TableA
set TableA.NodeName=TableA.NodeName + '?BadLink'
from TableA, TableB
where TableA.NodeID=TableB.NodeID
and TableB.NodeID=12345 --use this line if you want to update one row at a
time
"Andy" wrote:

> I am trying to update a field called NodeName from [Table A] to add the
> characters "?BadLink" to the end of the NodeName based on NodeID being equ
al
> to [Table B].NodeName. How can I do this?
> Example
> TableA.NodeID=12345 and TableB.NodeID=12345
> update the nodename "NameoftheNode" in table A to be "NameoftheNode?BadLin
k"
>

Sunday, February 12, 2012

Commad works but 0 rows effected

What does it mean when you have a querey like this

Update tblWatchInstance SET [NewInvoiceGen] = '1' Where tblWatchInstance.WatchID = '%" & txtWatchID.Text & "%'"

But when you run in the Qanalyzer it says 0 rows effected...why is that? could it be something i am missing.....

If you use equal sign in the where clause it will do a exact match. The watch ID has to match '%something%'

You might want to use like instead or skip the percent signs.

"Update tblWatchInstance SET [NewInvoiceGen] = '1' Where tblWatchInstance.WatchID like '%" & txtWatchID.Text & "%'"

"Update tblWatchInstance SET [NewInvoiceGen] = '1' Where tblWatchInstance.WatchID = ' & txtWatchID.Text & '"

First statement might match 0 or more (even all) while last only matches 0 or 1

NEVER concatenate user input directly into a SQL statement!!!

You open up for SQL Injection attack.

Edit: Have a look at parameterized queries instead. It says ASP.NET but it work in any .NET app. I choose this as it was #1 when I search for a link.

http://aspnet101.com/aspnet101/tutorials.aspx?id=1

Friday, February 10, 2012

comma delimited list update stored procedure

I have a stored procedure that I want to use to update multiple records. I'm using ASP and the request form collection is returning values in a comma delimited list.
Example:
name1 = value1, value2, value3, etc.
name2 = value1, value2, value3, etc.
name3 = value1, value2, value3, etc.

Here is how I wrote my stored procedure:

CREATE PROCEDURE dbo.Sp_Update_ABR_Record
(
@.abrID int,
@.ddo varchar(50),
@.ay varchar(50),
@.strategy varchar(10),
@.budgacct varchar(10),
@.budgobj varchar(10),
@.origamt
varchar(50),
@.incrdecr varchar(50),
@.review char(10),
@.abrdetlsID varchar(50)
)
AS
UPDATE DIM_ABR_REQ_HDR
SET ABR_review = @.review
WHERE ABR_ID = @.abrID

UPDATE DIM_ABR_REQ_DETLS
SET ABR_DETLS_DDO = @.ddo, ABR_DETLS_AY = @.ay,
ABR_DETLS_STRATEGY = @.strategy, ABR_DETLS_BUDG_ACCT = @.budgacct,
ABR_DETLS_BUDG_OBJ = @.budgobj, ABR_DETLS_FUND_ORIG_AMT = convert(money, @.origamt), ABR_DETLS_FUND_INCR_DECR = convert(money, @.incrdecr)
WHERE
ABR_DETLS_ID = @.abrdetlsID
GO

The second update is where the comma delimited list needs to be handled. The first update is only updating one field once.

Is there a way to write the procedure to handle the comma delimited list? Or, is the way I have the stored procedure okay and I just need to handle the comma delimited list within the ASP code? I'm not sure which way I can accomplish this?

Thanks for any help.
-D-Hi,
I think providing values in XML format rather than comma delimited will deliver more flexibility to retrieve values from that.
Still you can write User Defined Functions to pass the comma delimited string into that and get particular value.
Regards,
Leila|||Which parameter is the list, and how did you intend to use it?

-PatP|||The request form collection will return each of these parameters in a comma delimited list, which the second update in the stored procedure would handle:

@.ddo varchar(50),
@.ay varchar(50),
@.strategy varchar(10),
@.budgacct varchar(10),
@.budgobj varchar(10),
@.origamt varchar(50),
@.incrdecr varchar(50),
@.abrdetlsID varchar(50)

So, should I use the split function and pass the information into the procedure that way? I've used the split funciton for one parameter, but not multiple parameters. So, I wasn't sure how to code for that?

Thank you for your help.
-D-|||If the number of parameters the same across the set then do parse them and execute the procedure once for each combination. Otherwise, you need to review this design and get away from doing thing this way.|||Yes, there are the same number of parameters for each variable in the set. So, if I use the split function:

ddolist = Split(Request.Form("ddo"),", "
strategylist = Split(Request.Form("strategy"),", "
aylist = Split(Request.Form("ay"),", "
budgobjlist = Split(Request.Form("budgobj"),", "
budgacctlist = Split(Request.Form("budgacct"),", "
incrdecrlist = Split(Request.Form("incrdecr"),", "
abrdetlsIDlist = Split(Request.Form("abrdetlsID"),", "

I can use any of the parameters to determine the number of loops by using Ubound?

i.e.:

Loop_Max = UBound(abrdetlsIDlist)
For x = 0 to Loop_Max
Command_Name.Parameters.Item("@.ddo").Value = ddolist(x)
Command_Name.Parameters.Item("@.strategy").Value = strategylist(x)
Command_Name.Parameters.Item("@.ay").Value = aylist(x)
Command_Name.Parameters.Item("@.budgobj").Value = budgobjlist(x)
Command_Name.Parameters.Item("@.budgacct").Value = budgacctlist(x)
Command_Name.Parameters.Item("@.incrdecr").Value = incrdecrlist(x)
Command_Name.Parameters.Item("@.abrdetlsID").Value = abrdetlsIDlist(x)
Command_Name.Execute()
Next

Would that be correct?

Thank you for your help.
Regards,
-D-