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

Monday, March 26, 2012

Is there a delay writing to an SQL Database


Can someone advise if there is a delay in data being written to the database following a tableadapter.update(datatable) command?

I save transactions which are subjected to the above and then a listview is updated to reflect them.

As I work through all is OK and the transactions appear in view.

I then run a backup through my app using a backup object to do this and this reports all OK

I then close the app and re-open and as as I am in debug the database is empty.

I perform a restore through my app using a restore object and selecting the backup file I created previoulsy which reports all OK

The retore procedure calls application.restart to allow the app to initialise to the restored data.

The problem is quite a bit of my data in missing from the restore as if the last block I did prior to backup never actaully made it to the database?

I also rememeber noting that at times when the update method is performed the actual timestamp on the physical databse is not updated....until I close the app and return to the designer?

So does this mean then prior to performing a backup I have to somehow force the app to ensure it has written all changes to the databse?

Thanks

hi,

very loosely speaking, "updates" (as long as all operations) are always written to both data and log files..

log entries are immediately written in syncronous way, so that transactions can be later committed/rolled back even in case of a system crash... on the other side, physical flush to the database "data" files is performed at "scheduled" time (in async mode to boost underlying OS I/O activity and not to make the database service wait for completation aknowledge), that's to say at checkpoint occurrances...

but even if a crash occurs before the physical data flush to the data files, at next SQL Server start up the data will be recovered/rolled back (depending on completation and commit status of the relative transactions) when every and each database is started up, entering the "redo" and "undo" phases to check what still need to be written to data file(s) (to the actual tables) from the log file(s) analysing all active LSNs (log sequence number) in order to find what need to be serialized.. so, usually, you are not concerned with such a deal in your application if not in case of real disaster and database corruption as, again, even in case of a system crash the database, at next start up, must (and actually "is", if no corruption is on the air) recovered to a consistent state...

so, I'm guessing you are using the User Instance feature provided by SQLExpress..

I'm also guessing you set the "Copy to Ouput directory" property of your database file(s) to "Always" and that you took a backup of your "original" database and not the one you are interested in, that's to say the one you were working with at debug/run time..

is this the case?

regards

|||Hi, thanks for your explanation, this will prove useful.

I found out from another forum that when performing a backup/restore it is better to do it using the release version of the application rather than testing in the IDE!

Once I did this all worked well.

Friday, March 23, 2012

Is there a better way of doing an INSERT or UPDATE

I have several different situations where I want to
Update the record if it exists
or
add a new record if it does not exist.
An example might be
----
-- Has this table already got a record for this entry...
select @.rowcnt=count(*) from mytable where myField = '123'
if ( @.rowcnt = 0 )
begin ... NO so create the record with an initial cnt of 1
insert into mytable (myField, cnt) values ( 'text123', 1 )
end
else
begin -- ... YES so increment the cnt
Update mytable set cnt=cnt+1 where myField = 'text123'
end
---
The select count(*) can take a long time on a large table.
Table Structure something like
--
id PK
myField varchar(32)
cnt int
--
Thanks
BillTry:
If Exists (select * from mytable where myField = '123')
update ...
else
insert ...
The Exists will perform much better than the Count because it will stop as
soon as it hits a match.
"Bill" <wje@.blueyonder.co.uk> wrote in message
news:33ff429ctg88ethir0ej3g4plhfbr19sqo@.
4ax.com...
>I have several different situations where I want to
> Update the record if it exists
> or
> add a new record if it does not exist.
> An example might be
> ----
> -- Has this table already got a record for this entry...
> select @.rowcnt=count(*) from mytable where myField = '123'
> if ( @.rowcnt = 0 )
> begin ... NO so create the record with an initial cnt of 1
> insert into mytable (myField, cnt) values ( 'text123', 1 )
> end
> else
> begin -- ... YES so increment the cnt
> Update mytable set cnt=cnt+1 where myField = 'text123'
> end
> ---
> The select count(*) can take a long time on a large table.
> Table Structure something like
> --
> id PK
> myField varchar(32)
> cnt int
> --
> Thanks
> Bill|||The count(*) of your select will perform a scan on every record (either
indexed or otherwise) to find the number of instances. The higher the
rowcount, the longer it will take. Since it looks like (from your
example) that you are always looking to update exactly 1 row each time
use EXISTS instead. This will stop the reads once the record has been
located. Additionally, take a look at the indexes . . .:
if ( NOT EXISTS( select * from myTable where myField = '123') )
begin ... NO so create the record with an initial cnt of 1
insert into mytable (myField, cnt) values ( 'text123', 1 )
end
else
begin -- ... YES so increment the cnt
Update mytable set cnt=cnt+1 where myField = 'text123'
end
hope that helps . . .|||> The select count(*) can take a long time on a large table.
do you have a unique index on myField?|||Thanks very much.
Those replies were extremely useful.
Bill
On Thu, 20 Apr 2006 16:59:48 GMT, Bill <wje@.blueyonder.co.uk> wrote:

>I have several different situations where I want to
>Update the record if it exists
>or
>add a new record if it does not exist.
>An example might be
>----
>-- Has this table already got a record for this entry...
>select @.rowcnt=count(*) from mytable where myField = '123'
>if ( @.rowcnt = 0 )
> begin ... NO so create the record with an initial cnt of 1
> insert into mytable (myField, cnt) values ( 'text123', 1 )
> end
>else
> begin -- ... YES so increment the cnt
> Update mytable set cnt=cnt+1 where myField = 'text123'
> end
>---
>The select count(*) can take a long time on a large table.
>Table Structure something like
>--
>id PK
>myField varchar(32)
>cnt int
>--
>Thanks
>Bill|||As others have already pointed out, you can use exists instead of count(*),
but there's another problem with using the logic below in a concurrent
environment.
Here's what you need:
BEGIN TRAN
IF EXISTS (
SELECT *
FROM mytable WITH(UPDLOCK, HOLDLOCK)
WHERE myField = '123'
)
UPDATE...
ELSE
INSERT...
IF @.@.ERROR != 0 OR @.@.ROWCOUNT = 0
ROLLBACK
ELSE
COMMIT
What's most important here is the explicit transaction and WITH(UPDLOCK,
HOLDLOCK). Without these, you'll get inconsistent results in a concurrent
environment. Without the transaction, it's possible for another transaction
to delete the row between the time that the shared lock from the SELECT is
released and the time that the database engine tries to obtain an exclusive
lock for the UPDATE. Without both the transaction and HOLDLOCK, it's
possible for another transaction to insert a row where myField = '123'
between the time that EXISTS is evaluated and the time that the INSERT
starts executing. Without UPDLOCK, it's possible for two concurrent
instances to obtain and hold shared locks on the row where myField = '123'
such that neither can obtain an exclusive lock in order to do the UPDATE,
causing a deadlock. Now, that can happen only if the transaction isolation
level is stricter than READ COMMITTED, that is, REPEATABLE READ or
SERIALIZABLE. If the isolation level is READ COMMITTED (the default), then
other anomalies can occur, such as updates being lost, or primary key
constraint violations.
Thus, any time you issue a SELECT before an UPDATE or INSERT (even within an
EXISTS clause), you should wrap the whole thing in a transaction and
decorate the SELECT with the WITH(UPDLOCK, HOLDLOCK) clause. I prefer to
explicitly specify HOLDLOCK, even if the isolation level is SERIALIZABLE,
because that way if the isolation level is later changed (to improve
performance or scalability, for example), the above problems won't reappear.
"Bill" <wje@.blueyonder.co.uk> wrote in message
news:33ff429ctg88ethir0ej3g4plhfbr19sqo@.
4ax.com...
>I have several different situations where I want to
> Update the record if it exists
> or
> add a new record if it does not exist.
> An example might be
> ----
> -- Has this table already got a record for this entry...
> select @.rowcnt=count(*) from mytable where myField = '123'
> if ( @.rowcnt = 0 )
> begin ... NO so create the record with an initial cnt of 1
> insert into mytable (myField, cnt) values ( 'text123', 1 )
> end
> else
> begin -- ... YES so increment the cnt
> Update mytable set cnt=cnt+1 where myField = 'text123'
> end
> ---
> The select count(*) can take a long time on a large table.
> Table Structure something like
> --
> id PK
> myField varchar(32)
> cnt int
> --
> Thanks
> Bill|||One comment: Using NOT EXISTS will also force a table or index scan. The
query processor has to scan all records to determine if one is missing.
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another certification Exam
"epperly" <epperlys@.gmail.com> wrote in message
news:1145553039.015639.244770@.i39g2000cwa.googlegroups.com...
> The count(*) of your select will perform a scan on every record (either
> indexed or otherwise) to find the number of instances. The higher the
> rowcount, the longer it will take. Since it looks like (from your
> example) that you are always looking to update exactly 1 row each time
> use EXISTS instead. This will stop the reads once the record has been
> located. Additionally, take a look at the indexes . . .:
> if ( NOT EXISTS( select * from myTable where myField = '123') )
> begin ... NO so create the record with an initial cnt of 1
> insert into mytable (myField, cnt) values ( 'text123', 1 )
> end
> else
> begin -- ... YES so increment the cnt
> Update mytable set cnt=cnt+1 where myField = 'text123'
> end
> hope that helps . . .
>|||On Thu, 20 Apr 2006 22:01:01 -0700, "Arnie Rowland" <arnie@.1568.com>
wrote:

>One comment: Using NOT EXISTS will also force a table or index scan. The
>query processor has to scan all records to determine if one is missing.
First of all, if there is an index to support the subquery it will not
need to perform a scan.
Second, EXISTS performs exactly the same as NOT EXISTS. It has to, as
answering either question answers both questions.
Roy Harvey
Beacon Falls, CT

Is thee a log file that can tell when records were deleted

I do a monthly update that uses about 20+ DTS packages to import and
update SQL 2000 tables. I have a few tables that somehow get empty.
The update package does truncate the destination table then adds records
from the "staging" table into the destination table. Which works fine.
I tested it several times and when the individual package runs I have
data in the destination table. But when all packages are run, the data
gets removed. So I am thinking that buried in one of my packages it's
deleting the records. I have yet to find it. So is there a way to trap
when records get deleted from this table? An event or is their a log?
*** Sent via Developersdex http://www.examnotes.net ***
Don't just participate in USENET...get rewarded for it!http://www.aspfaq.com/2449
For the future:
http://www.aspfaq.com/2448
http://www.aspfaq.com/2496
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/
"Colin Colin" <ccole@.ghs.guthrie.org> wrote in message
news:uk6lbtx7DHA.2404@.TK2MSFTNGP11.phx.gbl...
> I do a monthly update that uses about 20+ DTS packages to import and
> update SQL 2000 tables. I have a few tables that somehow get empty.
> The update package does truncate the destination table then adds records
> from the "staging" table into the destination table. Which works fine.
> I tested it several times and when the individual package runs I have
> data in the destination table. But when all packages are run, the data
> gets removed. So I am thinking that buried in one of my packages it's
> deleting the records. I have yet to find it. So is there a way to trap
> when records get deleted from this table? An event or is their a log?
>
>
> *** Sent via Developersdex http://www.examnotes.net ***
> Don't just participate in USENET...get rewarded for it!sql

Is thee a log file that can tell when records were deleted

I do a monthly update that uses about 20+ DTS packages to import and
update SQL 2000 tables. I have a few tables that somehow get empty.
The update package does truncate the destination table then adds records
from the "staging" table into the destination table. Which works fine.
I tested it several times and when the individual package runs I have
data in the destination table. But when all packages are run, the data
gets removed. So I am thinking that buried in one of my packages it's
deleting the records. I have yet to find it. So is there a way to trap
when records get deleted from this table? An event or is their a log?
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!http://www.aspfaq.com/2449
For the future:
http://www.aspfaq.com/2448
http://www.aspfaq.com/2496
--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/
"Colin Colin" <ccole@.ghs.guthrie.org> wrote in message
news:uk6lbtx7DHA.2404@.TK2MSFTNGP11.phx.gbl...
> I do a monthly update that uses about 20+ DTS packages to import and
> update SQL 2000 tables. I have a few tables that somehow get empty.
> The update package does truncate the destination table then adds records
> from the "staging" table into the destination table. Which works fine.
> I tested it several times and when the individual package runs I have
> data in the destination table. But when all packages are run, the data
> gets removed. So I am thinking that buried in one of my packages it's
> deleting the records. I have yet to find it. So is there a way to trap
> when records get deleted from this table? An event or is their a log?
>
>
> *** Sent via Developersdex http://www.developersdex.com ***
> Don't just participate in USENET...get rewarded for it!

Wednesday, March 21, 2012

Is the behavior of this UPDATE SQL expected or a Bug?

Hi All,
I am using SQLServer 2000 with ServicePack 3a. Can any one tell me if the
following Update SQLis a bug or expected behavior?
CREATE TABLE [Table1] (
[col1] [int] NULL ,
[col2] [int] NULL
)
GO
CREATE TABLE [Table2] (
[col1] [int] NULL ,
[col3] [int] NULL
)
GO
insert into table1 (col1, col2) values (1,null)
insert into table1 (col1, col2) values (2,null)
insert into table2 (col1, col3) values (1,11)
insert into table2 (col1, col3) values (1,12)
insert into table2 (col1, col3) values (2,22)
go
-- Here is the UPDATE SQL. I am trying to update col2 of Table1 with
-- col3 of Table2
update table1
set col2=b.col3
from table1 a, table2 b
where a.col1=b.col1
I was expecting that the above SQL should fail because in this JOIN between
two tables there are two rows fetched from table2 for first row in table1
But against to my expectations that SQL was successful and got message
(2 row(s) affected)
And first row in table1, it has updated col2 with value 12
Am I making sense?
Thanks in advance,
Vinod"VM" <VM@.discussions.microsoft.com> wrote in message
news:4F375926-71A9-4CCD-9119-7D336F7809A4@.microsoft.com...
> Hi All,
> I am using SQLServer 2000 with ServicePack 3a. Can any one tell me if the
> following Update SQLis a bug or expected behavior?
> CREATE TABLE [Table1] (
> [col1] [int] NULL ,
> [col2] [int] NULL
> )
> GO
> CREATE TABLE [Table2] (
> [col1] [int] NULL ,
> [col3] [int] NULL
> )
> GO
> insert into table1 (col1, col2) values (1,null)
> insert into table1 (col1, col2) values (2,null)
> insert into table2 (col1, col3) values (1,11)
> insert into table2 (col1, col3) values (1,12)
> insert into table2 (col1, col3) values (2,22)
> go
> -- Here is the UPDATE SQL. I am trying to update col2 of Table1 with
> -- col3 of Table2
> update table1
> set col2=b.col3
> from table1 a, table2 b
> where a.col1=b.col1
>
> I was expecting that the above SQL should fail because in this JOIN
> between
> two tables there are two rows fetched from table2 for first row in table1
> But against to my expectations that SQL was successful and got message
> (2 row(s) affected)
>
> And first row in table1, it has updated col2 with value 12
> Am I making sense?
> Thanks in advance,
> Vinod
>
You are absolutely right to be concerned. Unfortunately this is the expected
behaviour. Books Online:
"The results of an UPDATE statement are undefined if the statement includes
a FROM clause that is not specified in such a way that only one value is
available for each column occurrence that is updated, that is if the UPDATE
statement is not deterministic."
So you get random results by design! If you want to use the UPDATE FROM
syntax then be very sure your join returns unique rows. If in doubt you may
prefer to use the ANSI standard syntax, which does fail safe:
UPDATE table1
SET col2 =
(SELECT col3
FROM table2
WHERE col1 = table1.col1);
Result:
Server: Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery
follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||Vinod,
The first thing to understand about this situation is that the ANSI
standard does not allow a FROM clause in an UPDATE command. The
reason it does not is the ambiguity that you are asking about - if
there are two matching rows, which one provides the value?
The answer is that when using a FROM clause in an UPDATE, and joining
to a table with multiple rows matching a single row being updated, you
can not predict which row will contribute the value that ends up in
the matching row.
I have not tested in recent years, but at least in release 6.5 and
beyond there would have been TWO rows in the log, one for each match,
even though the "row(s) affected" would only count the row updated
once. That used to be - may still be - a great way to make the log
get really big very quickly; update OrderMaster by joining to
OrderItem, with an average of ten items per master, and log ten
updates for each row.
Hope that helps.
Roy
On Wed, 15 Feb 2006 15:55:27 -0800, "VM"
<VM@.discussions.microsoft.com> wrote:

>Hi All,
>I am using SQLServer 2000 with ServicePack 3a. Can any one tell me if the
>following Update SQLis a bug or expected behavior?
>CREATE TABLE [Table1] (
> [col1] [int] NULL ,
> [col2] [int] NULL
> )
>GO
>CREATE TABLE [Table2] (
> [col1] [int] NULL ,
> [col3] [int] NULL
> )
>GO
>insert into table1 (col1, col2) values (1,null)
>insert into table1 (col1, col2) values (2,null)
>insert into table2 (col1, col3) values (1,11)
>insert into table2 (col1, col3) values (1,12)
>insert into table2 (col1, col3) values (2,22)
>go
>-- Here is the UPDATE SQL. I am trying to update col2 of Table1 with
>-- col3 of Table2
>update table1
>set col2=b.col3
>from table1 a, table2 b
>where a.col1=b.col1
>
>I was expecting that the above SQL should fail because in this JOIN between
>two tables there are two rows fetched from table2 for first row in table1
>But against to my expectations that SQL was successful and got message
>(2 row(s) affected)
>
>And first row in table1, it has updated col2 with value 12
>Am I making sense?
>Thanks in advance,
>Vinod
>|||David and Roy,
Thankyou so much for your replies. Now I have good picture about the FROM
clause in UPDATE statement. I will be very careful from now.
Again, Thanks guys!!
Vinod
"Roy Harvey" wrote:

> Vinod,
> The first thing to understand about this situation is that the ANSI
> standard does not allow a FROM clause in an UPDATE command. The
> reason it does not is the ambiguity that you are asking about - if
> there are two matching rows, which one provides the value?
> The answer is that when using a FROM clause in an UPDATE, and joining
> to a table with multiple rows matching a single row being updated, you
> can not predict which row will contribute the value that ends up in
> the matching row.
> I have not tested in recent years, but at least in release 6.5 and
> beyond there would have been TWO rows in the log, one for each match,
> even though the "row(s) affected" would only count the row updated
> once. That used to be - may still be - a great way to make the log
> get really big very quickly; update OrderMaster by joining to
> OrderItem, with an average of ten items per master, and log ten
> updates for each row.
> Hope that helps.
> Roy
>
> On Wed, 15 Feb 2006 15:55:27 -0800, "VM"
> <VM@.discussions.microsoft.com> wrote:
>
>

Friday, February 24, 2012

IS NULL in SQL statement

Hi,
I am trying to update a table where a field is set to null. The query is:
UPDATE U_segment
SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
FROM U_segment
INNER JOIN U_T_STEP02A
ON U_segment.REF = U_T_STEP02A.REF
WHERE U_segment.SEGMENT ISNULL
It's not liking it at all.
Any help would be appreciated
Rob
> WHERE U_segment.SEGMENT ISNULL
Above should be:
WHERE U_segment.SEGMENT IS NULL
Note the space between the words IS and NULL.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Robert" <Robert@.discussions.microsoft.com> wrote in message
news:DB39722D-833F-4C99-8F8A-E219E002A6DA@.microsoft.com...
> Hi,
> I am trying to update a table where a field is set to null. The query is:
> UPDATE U_segment
> SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
> FROM U_segment
> INNER JOIN U_T_STEP02A
> ON U_segment.REF = U_T_STEP02A.REF
> WHERE U_segment.SEGMENT ISNULL
> It's not liking it at all.
> Any help would be appreciated
> Rob
|||"IS NULL" --> "IS[thisisablank]NULL"
ISNULL is a function which has a signature like ISNULL(Expression,
Valueifexpressionisnull).
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
"Robert" <Robert@.discussions.microsoft.com> schrieb im Newsbeitrag
news:DB39722D-833F-4C99-8F8A-E219E002A6DA@.microsoft.com...
> Hi,
> I am trying to update a table where a field is set to null. The query is:
> UPDATE U_segment
> SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
> FROM U_segment
> INNER JOIN U_T_STEP02A
> ON U_segment.REF = U_T_STEP02A.REF
> WHERE U_segment.SEGMENT ISNULL
> It's not liking it at all.
> Any help would be appreciated
> Rob
|||I think you need to have space between IS and NULL -> IS NULL instead of
ISNULL
Regards
Steen
"Robert" <Robert@.discussions.microsoft.com> skrev i en meddelelse
news:DB39722D-833F-4C99-8F8A-E219E002A6DA@.microsoft.com...
> Hi,
> I am trying to update a table where a field is set to null. The query is:
> UPDATE U_segment
> SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
> FROM U_segment
> INNER JOIN U_T_STEP02A
> ON U_segment.REF = U_T_STEP02A.REF
> WHERE U_segment.SEGMENT ISNULL
> It's not liking it at all.
> Any help would be appreciated
> Rob

IS NULL in SQL statement

Hi,
I am trying to update a table where a field is set to null. The query is:
UPDATE U_segment
SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
FROM U_segment
INNER JOIN U_T_STEP02A
ON U_segment.REF = U_T_STEP02A.REF
WHERE U_segment.SEGMENT ISNULL
It's not liking it at all.
Any help would be appreciated
Rob> WHERE U_segment.SEGMENT ISNULL
Above should be:
WHERE U_segment.SEGMENT IS NULL
Note the space between the words IS and NULL.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Robert" <Robert@.discussions.microsoft.com> wrote in message
news:DB39722D-833F-4C99-8F8A-E219E002A6DA@.microsoft.com...
> Hi,
> I am trying to update a table where a field is set to null. The query is:
> UPDATE U_segment
> SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
> FROM U_segment
> INNER JOIN U_T_STEP02A
> ON U_segment.REF = U_T_STEP02A.REF
> WHERE U_segment.SEGMENT ISNULL
> It's not liking it at all.
> Any help would be appreciated
> Rob|||"IS NULL" --> "IS[thisisablank]NULL"
ISNULL is a function which has a signature like ISNULL(Expression,
Valueifexpressionisnull).
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"Robert" <Robert@.discussions.microsoft.com> schrieb im Newsbeitrag
news:DB39722D-833F-4C99-8F8A-E219E002A6DA@.microsoft.com...
> Hi,
> I am trying to update a table where a field is set to null. The query is:
> UPDATE U_segment
> SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
> FROM U_segment
> INNER JOIN U_T_STEP02A
> ON U_segment.REF = U_T_STEP02A.REF
> WHERE U_segment.SEGMENT ISNULL
> It's not liking it at all.
> Any help would be appreciated
> Rob|||I think you need to have space between IS and NULL -> IS NULL instead of
ISNULL
Regards
Steen
"Robert" <Robert@.discussions.microsoft.com> skrev i en meddelelse
news:DB39722D-833F-4C99-8F8A-E219E002A6DA@.microsoft.com...
> Hi,
> I am trying to update a table where a field is set to null. The query is:
> UPDATE U_segment
> SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
> FROM U_segment
> INNER JOIN U_T_STEP02A
> ON U_segment.REF = U_T_STEP02A.REF
> WHERE U_segment.SEGMENT ISNULL
> It's not liking it at all.
> Any help would be appreciated
> Rob

IS NULL in SQL statement

Hi,
I am trying to update a table where a field is set to null. The query is:
UPDATE U_segment
SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
FROM U_segment
INNER JOIN U_T_STEP02A
ON U_segment.REF = U_T_STEP02A.REF
WHERE U_segment.SEGMENT ISNULL
It's not liking it at all.
Any help would be appreciated
Rob> WHERE U_segment.SEGMENT ISNULL
Above should be:
WHERE U_segment.SEGMENT IS NULL
Note the space between the words IS and NULL.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Robert" <Robert@.discussions.microsoft.com> wrote in message
news:DB39722D-833F-4C99-8F8A-E219E002A6DA@.microsoft.com...
> Hi,
> I am trying to update a table where a field is set to null. The query is:
> UPDATE U_segment
> SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
> FROM U_segment
> INNER JOIN U_T_STEP02A
> ON U_segment.REF = U_T_STEP02A.REF
> WHERE U_segment.SEGMENT ISNULL
> It's not liking it at all.
> Any help would be appreciated
> Rob|||"IS NULL" --> "IS[thisisablank]NULL"
ISNULL is a function which has a signature like ISNULL(Expression,
Valueifexpressionisnull).
--
HTH, Jens Suessmeyer.
--
http://www.sqlserver2005.de
--
"Robert" <Robert@.discussions.microsoft.com> schrieb im Newsbeitrag
news:DB39722D-833F-4C99-8F8A-E219E002A6DA@.microsoft.com...
> Hi,
> I am trying to update a table where a field is set to null. The query is:
> UPDATE U_segment
> SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
> FROM U_segment
> INNER JOIN U_T_STEP02A
> ON U_segment.REF = U_T_STEP02A.REF
> WHERE U_segment.SEGMENT ISNULL
> It's not liking it at all.
> Any help would be appreciated
> Rob|||I think you need to have space between IS and NULL -> IS NULL instead of
ISNULL
Regards
Steen
"Robert" <Robert@.discussions.microsoft.com> skrev i en meddelelse
news:DB39722D-833F-4C99-8F8A-E219E002A6DA@.microsoft.com...
> Hi,
> I am trying to update a table where a field is set to null. The query is:
> UPDATE U_segment
> SET SEGMENT = '2A-Legacy Pledges Committed-MULTI'
> FROM U_segment
> INNER JOIN U_T_STEP02A
> ON U_segment.REF = U_T_STEP02A.REF
> WHERE U_segment.SEGMENT ISNULL
> It's not liking it at all.
> Any help would be appreciated
> Rob

Monday, February 20, 2012

Is my UPDATE statement buggy?

QA has told me that on two occassions the following sp updated all rows to
the same @.BillerID value. Could this happen? Is my TSQL buggy? This is the
last step of a lengthy data migration process. The SPs are executed by a
C#/.Net forms app.
DDL statements for all three tables follow (Payer and PayerXref exist in
seperate database on the same server). Thanks in advance.
--The SP
/*
CREATED BY: KEVIN WILLIAMS
CREATED ON: 10/24/2005
NOTES:
will set the BillerId fields in PayerDB.dbo.Payer and PayerDB.dbo.Account to
the BillerId
passed by the user.
These fields now hold the primary key of the V3 tables
*/
CREATE PROCEDURE dbo.usp_MigratePayerService_BillerId
@.CREDID BIGINT,
@.BILLERID BIGINT
AS
DECLARE @.errnum INT
SET NOCOUNT ON
----
UPDATE PayerDB.dbo.Payer
SET BillerId = @.BILLERID
FROM Migration.dbo.PayerXref X
JOIN PayerDB.dbo.Payer P
ON(X.AccountUserID = P.BillerId)
WHERE X.BillerId = @.BILLERID
----
SET @.errnum = @.@.ERROR
IF @.errnum<>0
BEGIN
GOTO BAILOUT
END
----
UPDATE PayerDB.dbo.Account
SET BillerId = @.BILLERID
FROM Migration.dbo.AccountXref X
JOIN PayerDB.dbo.Account A
ON(X.AccountID_TP3 = A.BillerId)
WHERE x.BillerId = @.BILLERID
----
SET @.errnum = @.@.ERROR
----
BAILOUT:
RETURN @.errnum
--End of SP
--Create statements for tables
CREATE TABLE dbo.Payer
(PayerId bigint IDENTITY (1, 1) NOT NULL ,
Identifier varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
BillerId bigint NOT NULL)
--other fields removed for sake of space
CREATE TABLE dbo.PayerXref
(AccountUserID bigint NOT NULL ,
PayerId bigint NULL ,
BillerId bigint NOT NULL ,
Migrated bit NOT NULL CONSTRAINT DF_PayerXref_Migrated DEFAULT (0),
ErrorDescription varchar (4000) COLLATE Latin1_General_CI_AS NULL)instead of:
UPDATE PayerDB.dbo.Payer
SET BillerId = @.BILLERID
FROM Migration.dbo.PayerXref X
JOIN PayerDB.dbo.Payer P
ON(X.AccountUserID = P.BillerId)
WHERE X.BillerId = @.BILLERID
use the alias, P:
UPDATE P
SET BillerId = @.BILLERID
FROM Migration.dbo.PayerXref X
JOIN PayerDB.dbo.Payer P
ON(X.AccountUserID = P.BillerId)
WHERE X.BillerId = @.BILLERID
kevin wrote:
> QA has told me that on two occassions the following sp updated all rows t
o
> the same @.BillerID value. Could this happen? Is my TSQL buggy? This is t
he
> last step of a lengthy data migration process. The SPs are executed by a
> C#/.Net forms app.
> DDL statements for all three tables follow (Payer and PayerXref exist in
> seperate database on the same server). Thanks in advance.
> --The SP
> /*
> CREATED BY: KEVIN WILLIAMS
> CREATED ON: 10/24/2005
> NOTES:
> will set the BillerId fields in PayerDB.dbo.Payer and PayerDB.dbo.Account
to
> the BillerId
> passed by the user.
> These fields now hold the primary key of the V3 tables
> */
> CREATE PROCEDURE dbo.usp_MigratePayerService_BillerId
> @.CREDID BIGINT,
> @.BILLERID BIGINT
> AS
> DECLARE @.errnum INT
> SET NOCOUNT ON
> ----
> UPDATE PayerDB.dbo.Payer
> SET BillerId = @.BILLERID
> FROM Migration.dbo.PayerXref X
> JOIN PayerDB.dbo.Payer P
> ON(X.AccountUserID = P.BillerId)
> WHERE X.BillerId = @.BILLERID
> ----
> SET @.errnum = @.@.ERROR
> IF @.errnum<>0
> BEGIN
> GOTO BAILOUT
> END
> ----
> UPDATE PayerDB.dbo.Account
> SET BillerId = @.BILLERID
> FROM Migration.dbo.AccountXref X
> JOIN PayerDB.dbo.Account A
> ON(X.AccountID_TP3 = A.BillerId)
> WHERE x.BillerId = @.BILLERID
> ----
> SET @.errnum = @.@.ERROR
> ----
> BAILOUT:
> RETURN @.errnum
> --End of SP
> --Create statements for tables
> CREATE TABLE dbo.Payer
> (PayerId bigint IDENTITY (1, 1) NOT NULL ,
> Identifier varchar (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> BillerId bigint NOT NULL)
> --other fields removed for sake of space
> CREATE TABLE dbo.PayerXref
> (AccountUserID bigint NOT NULL ,
> PayerId bigint NULL ,
> BillerId bigint NOT NULL ,
> Migrated bit NOT NULL CONSTRAINT DF_PayerXref_Migrated DEFAULT (0),
> ErrorDescription varchar (4000) COLLATE Latin1_General_CI_AS NULL)
>|||Thanks for the input Dave.
Please explain how yours is different than mine... other than less typing?
Kevin
"Dave Markle" <"dma[remove_ZZ]ZZrkle" wrote:

> instead of:
> UPDATE PayerDB.dbo.Payer
> SET BillerId = @.BILLERID
> FROM Migration.dbo.PayerXref X
> JOIN PayerDB.dbo.Payer P
> ON(X.AccountUserID = P.BillerId)
> WHERE X.BillerId = @.BILLERID
> use the alias, P:
> UPDATE P
> SET BillerId = @.BILLERID
> FROM Migration.dbo.PayerXref X
> JOIN PayerDB.dbo.Payer P
> ON(X.AccountUserID = P.BillerId)
> WHERE X.BillerId = @.BILLERID
>
> kevin wrote:
>|||Sorry, it was ambiguous to me, but it after running some tests to
convince myself, it wasn't ambiguous to SQL Server.
Anyway, what's your data look like? Can you post the DDL of those two
tables? I don't see a problem with your T-SQL, per se.
-Dave
kevin wrote:
> Thanks for the input Dave.
> Please explain how yours is different than mine... other than less typing?
> Kevin
> "Dave Markle" <"dma[remove_ZZ]ZZrkle" wrote:
>|||You do know that the proprietrary UPDATE.. FROM syntax is ambigous and
not portable? First it r makes no sense in terms of the SQL language
model. A FROM clause is always suppose effectively materialize a
working table that disappears at the end of the statement. Likewise,
an alias is supposed to act as it materializes a new working table with
the data from the original table expression in it. To be consistent,
this syntax says that you have done nothing to the base table.
Sybase and some other vendors had the same syntax but with different
semantics. Worst of both worlds!
And on top of that, it is unpredictable. This is a simple example from
Adam Machanic
CREATE TABLE Foo
(col_a CHAR(1) NOT NULL,
col_b INTEGER NOT NULL);
INSERT INTO Foo VALUES ('A', 0);
INSERT INTO Foo VALUES ('B', 0);
INSERT INTO Foo VALUES ('C', 0);
CREATE TABLE Bar
(col_a CHAR(1) NOT NULL,
col_b INTEGER NOT NULL);
INSERT INTO Bar VALUES ('A', 1);
INSERT INTO Bar VALUES ('A', 2);
INSERT INTO Bar VALUES ('B', 1);
INSERT INTO Bar VALUES ('C', 1);
You run this proprietary UPDATE with a FROM clause:
UPDATE Foo
SET Foo.col_b = Bar.col_b
FROM Foo INNER JOIN Bar
ON Foo.col_a = Bar.col_a;
The result of the update cannot be determined. The value of the column
will depend upon either order of insertion, (if there are no clustered
indexes present), or on order of clustering (but only if the cluster
isn't fragmented).
What you wanted was more like this:
UPDATE Payers -- more than one?
SET biller_id = @.my_biller_id
WHERE EXISTS
(SELECT *
FROM Migration.bo.PayerXref AS X
WHERE X.account_user_id = Payers.biller_id);
UPDATE Accounts
SET biller_id = @.my_biller_id
WHERE EXISTS
(SELECT *
FROM Migration.bo.PayerXref AS X
WHERE X.account_user_id_tp3 = Payers.biller_id);
How many different names does the biller_id data element have/ At
least three names for the *same* data element, which is proof that the
design is a screwed up mess.
The DDL you did post made no sense. No keys, names like "identifier"
that is huge (the only real code I know that is that long is the IBAN),
you have biller_id in a Payers table, NULLs where they should not be,
etfc.|||--CELKO--,
Thanks for your input.

> How many different names does the biller_id data element have/ At
> least three names for the *same* data element, which is proof that the
> design is a screwed up mess.
Not sure what you exactly mean by "different names". The biller is our
customer and the payer is the biller's customer. its a one to many
relationship. Payers may have many Accounts. One-to-Many again. If you ar
e
referring to the fact that the biller_id is on both tables, I agree with you
(see #1 below).

> The DDL you did post made no sense. No keys, names like "identifier"
> that is huge (the only real code I know that is that long is the IBAN),
> you have biller_id in a Payers table, NULLs where they should not be,
> etfc.
See #3 below
1. I am simply the contractor migrating data from an old db schema to a new
one. I did not design the layout or select the object names so I have no
need to defend or explain them. Even so, what is so reprehensible about
"Identifier" as a field name and how do you "know" that there are "...NULLs
where they should not be"? Shouldn't they be where your business needs say
they should be?
2. About proprietary syntax: I am using SQL Server and not SYBASE or SAS or
MYSQL etc. This is a SQL Server forum, not an ANSI SQL forum. My employer
is 100% Microsoft pimped and a damn good Ho at that. A Ho would be a fool
not to ride in the Pimp's caddy. She paid for it!
3.The Payer table does have a primary key on the IDENTITY field. I assumed
that that was a given... but there is a saying about assuming.
CREATE TABLE [dbo].[Payer] (
[PayerId] [bigint] IDENTITY (1, 1) NOT NULL ,
[Identifier] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[BillerId] [bigint] NOT NULL ,
[FirstName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[LastName] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[EmailAddress] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Street1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Street2] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[City] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[StateCode] [varchar] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[CountryCode] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
CONSTRAINT [DF_Payer_CountryCode] DEFAULT ('USA'),
[PostalCode] [varchar] (9) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[PasswordHash] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[PIN] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Phone] [varchar] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[PersistPaymentInfo] [bit] NOT NULL CONSTRAINT
[DF_Payer_PersistPaymentInfo] DEFAULT (1),
[ExpirationDate] [datetime] NULL ,
[Created] [datetime] NOT NULL CONSTRAINT [DF_Payer_Created] DEFAULT
(getdate()),
[CreatedBy] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
CONSTRAINT [DF_Payer_CreatedBy] DEFAULT ('System'),
[Modified] [datetime] NULL ,
[ModifiedBy] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[rowguid] uniqueidentifier ROWGUIDCOL NOT NULL CONSTRAINT
[DF__Payer__rowguid__3D7E1B63] DEFAULT (newid()),
CONSTRAINT [PK_payer_1] PRIMARY KEY CLUSTERED
(
[PayerId]
) ON [PRIMARY]
) ON [PRIMARY]
GO

Is multiple action trigger possible

Hello

Is it possible to create a trigger with multiple actions?

I would like to create a trigger with INSERT, DELETE, UPDATE funtions but I have not been above to find a clear syntax example

Below I have created a statement of my trigger. Could somebody please confirm if the syntac in this multiple action trigger is ok.multple actions on a single trigger

Is this syntax correct?

CREATE TRIGGER [dbo].[trig_AddDomCatA]
ON DomainNames
For INSERT, DELETE, UPDATE

AS

INSERT INTO Domain_CatA (DomainName)
SELECT DomainName FROM INSERTED


AS
DELETE FROM Domain_CatA (DomainName)
SELECT DomainName FROM DELETED


AS
UPDATE INTO Domain_CatA (DomainName)
SELECT DomainName FROM UPDATED

Thanks

Lynn

Why do you need triggers?

Is it possible to add the required actions to the insert, update and delete stored procedures?

|||

you have to split the insert/update from the delete trigger.

CREATE TRIGGER [dbo].[trig_AddDomCatA]
ON DomainNames
For INSERT, UPDATE

AS

INSERT INTO Domain_CatA (DomainName)
SELECT DomainName FROM INSERTED

GO

CREATE TRIGGER [dbo].[trig_AddDomCatA]
ON DomainNames
For DELETE

AS

DELETE FROM Domain_CatA (DomainName)
SELECT DomainName FROM DELETED


|||

Hello TATWORTH

Thanks for the reply.

Yes it is possible to use, insert, update and delete stored procedures, which is the current method I am using. However, as I have the same list of data on 26 categories tabes from A-Z, I thought it would be a more speedier and efficient method instead of using stored procedures.

Is there a good reason not to use triggers instead of stored procedures?

Thanks

Lynn

|||

Hello khtan

Thanks for the reply and detailed explanation.

Lynn

|||

>>Is there a good reason not to use triggers instead of stored procedures?

Stored procedures will give you better and more consistent performance. It has been known for triggers that function well during development, bring a production system to its knees. Stored procedures are better for another reason - all the components of an action is brought into one place thus they can be designed as a whole, reviewed as a whole and maintained as a whole.

I fully realise that many DBAs get excellant milage out of triggers, however in 10+ years of designing some 20 SQL server database, I have used triggers once and that was because I though a fellow DBA might enter some data by hand.

|||

Hello TATWORTH

Thanks for the information. I thought that a trigger would save me the task of entering the same stored procedure 26 times. Now repetitive stored procedures do not seem like too much of a chore.

Thanks

|||Just open up all the s.p. in SQL Management Studio and copy and paste ... copy and paste .. copy and paste!