T-SQL cursor and update - sql

I use a cursor to iterate through quite a big table. For each row I check if value from one column exists in other.
If the value exists, I would like to increase value column in that other table.
If not, I would like to insert there new row with value set to 1.
I check "if exists" by:
IF (SELECT COUNT(*) FROM otherTabe WHERE... > 1)
BEGIN
...
END
ELSE
BEGIN
...
END
I don't know how to get that row which was found and update value. I don't want to make another select.
How can I do this efficiently?
I assume that the method of checking described above isn't good for this case.

Depending on the size of your data and the actual condition, you have two basic approaches:
1) use MERGE
MERGE TOP (...) INTO table1
USING table2 ON table1.column = table2.column
WHEN MATCHED
THEN UPDATE SET table1.counter += 1
WHEN NOT MATCHED SOURCE
THEN INSERT (...) VALUES (...);
the TOP is needed because when you're doing a huge update like this (you mention the table is 'big', big is relative, but lets assume truly big, +100MM rows) you have to batch the updates, otherwise you'll overwhelm the transaction log with one single gigantic transaction.
2) use a cursor, as you are trying. Your original question can be easily solved, simply always update and then check the count of rows updated:
UPDATE table
SET column += 1
WHERE ...;
IF ##ROW_COUNT = 0
BEGIN
-- no match, insert new value
INSERT INTO (...) VALUES (...);
END
Note that this approach is dangerous though because of race conditions: there is nothing to prevent another thread from inserting the value concurrently, so you may end up with either duplicates or a constraint violation error (preferably the latter...).

This is just psuedo code because I have no idea of your table structure but I think you will understand... basically Update the columns you want then Insert the columns you need. A Cursor operation sounds unnecessary.
Update OtherTable
Set ColumnToIncrease = ColumnToIncrease + 1
FROM CurrentTable Where ColumnToCheckValue is not null
Insert Into OtherTable (ColumnToIncrease, Field1, Field2,...)
SELECT
1,
?
?
FROM CurrentTable Where ColumnToCheckValue is not null

Without a sample, I think this is the best I can do. Bottom line: you don't need a cursor. UPDATE where a match exists (INNER JOIN) and INSERT where one does not.
UPDATE otherTable
SET IncrementingColumn = IncrementingColumn + 1
FROM thisTable INNER JOIN otherTable ON thisTable.ID = otherTable.ID
INSERT INTO otherTable
(
ID
, IncrementingColumn
)
SELECT ID, 1
FROM thisTable
WHERE NOT EXISTS (SELECT *
FROM otherTable
WHERE thisTable.ID = otherTable.ID)

I think you'd be better off using a view for this -- then it's always up to date, no risk of mistakenly double/triple/etc counting:
CREATE VIEW vw_value_count AS
SELECT st.value,
COUNT(*) AS numValue
FROM SOME_TABLE st
GROUP BY st.value
But if you still want to use the INSERT/UPDATE approach:
IF EXISTS(SELECT NULL
FROM SOMETABLE WHERE ... > 1)
BEGIN
UPDATE TABLE
SET count = count + 1
WHERE value = #value
END
ELSE
BEGIN
INSERT INTO TABLE
(value, count)
VALUES
(#value, 1)
END

What about Update statement with inner join to perform +1, and Insert selected rows that do not exist in the first table.
Provide the tables schema and the columns you want to check and update so I can help.
Regards.

Related

SQL Server trigger to update another table's column

I have two SQL Server tables called Table A and Table B. I have an application which inserts one row into Table A and three rows into Table B at the same time. As you can see in the screenshot below, we can link these inserted records based on their ID column in Table A and TransID column in Table B.
During the data insert on table B, if any rows out of 3 inserted rows contain a value called Printed in the Printed column, I want to update my Table A's relevant record's PrintStatus column to Printed as well.
How do I write a SQL Server trigger for this?
Well the best solution is to do this in your code(app) but if there is no way,
you can write a Trigger After Insert for Table B like the trigger example below:
CREATE TRIGGER [dbo].[YourTrigger] ON [dbo].[TableB]
AFTER INSERT
AS
DECLARE #id INT
BEGIN
SET NOCOUNT ON;
SET #id = (SELECT DISTINCT ID FROM Inserted)
IF EXISTS (SELECT * FROM Inserted WHERE Printed='Printed')
UPDATE TableA
SET PrintStatus='Printed'
WHERE ID = #id
END
May this help you
It could be correct for your problem : (not sure at 100%)
CREATE TRIGGER TriggerTableB
ON TableB
AFTER INSERT
AS
UPDATE TableA AS A
SET PrintStatus = 'Printed'
WHERE A.TranID = inserted.ID
AND 'Printed' = (SELECT MAX(I.Printed)
FROM inserted AS I)
I would recommend querying for the information:
select a.*,
(case when exists (select 1
from b
where b.id = a.tranid and b.printed = 'Printed'
)
then 'Printed'
end) as printstatus
from a;
This is simpler than writing a query and you can wrap this in a view.
From a performance perspective, an index on b(id, printed) should make this pretty fast -- and not slow down inserts.
A trigger can be quite complicated, if you want to take inserts, updates, and deletes into account. I prefer to avoid such complication, if possible.

Oracle SQL, trying to get one value from a select/join to use to update one column in one table?

I have one table with the following columns:
T_RESOLVED_DATE
I_HOUSEHOLD_NUMBER
I_RESOLVED_SET_NUMBER
I_STATION_CODE
I_RESOLVED_START_MIN
I_DURATION
I_PERSON_NUMBER
I_COVIEW_DEMO_ID
Initially, I_COVIEW_DEMO_ID is set to null.
Then I have another table with the following columns:
T_RESOLVED_DATE
I_HOUSEHOLD_NUMBER
I_PERSON_NUMBER
I_AGE
T_GENDER
I_COVIEW_DEMO_ID
I am trying to update I_COVIEW_DEMO_ID in the first table by using the value of I_COVIEW_DEMO_ID in the second table where the T_RESOLVED_DATE, I_HOUSEHOLD_NUMBER, and I_PERSON_NUMBER are equal in both tables. The first table may contain multiple rows with the same DATE, HOUSEHOLD_NUMBER, and PERSON_NUMBER, because the rows can vary by the rest of the columns.
I have tried to do a select and a group by which seems to get me part way there, but I am getting a "single-row subquery returns more than one row" error when I try to update the columns in the first table. This is what I've tried, along with variations of it:
UPDATE
Table1
SET
I_COVIEW_DEMO_ID =
(SELECT
b.I_COVIEW_DEMO_ID
FROM Table1 a,
Table2 b
WHERE a.I_HOUSEHOLD_NUMBER = b.I_HOUSEHOLD_NUMBER AND
a.I_PERSON_NUMBER = b.I_PERSON_NUMBER AND
a.T_RESOLVED_DATE = b.T_RESOLVED_DATE
GROUP BY b.I_COVIEW_DEMO_ID);
Any suggestions?
I was able to get it to work using this statement:
MERGE INTO table1 a
USING
(
SELECT DISTINCT
T_RESOLVED_DATE,
I_HOUSEHOLD_NUMBER,
I_PERSON_NUMBER,
I_COVIEW_DEMO_ID
FROM
table2
) b
ON
(
a.T_RESOLVED_DATE = b.T_RESOLVED_DATE
AND a.I_HOUSEHOLD_NUMBER = b.I_HOUSEHOLD_NUMBER
AND a.I_PERSON_NUMBER = b.I_PERSON_NUMBER
) WHEN MATCHED THEN
UPDATE SET
a.I_COVIEW_DEMO_ID = b.I_COVIEW_DEMO_ID;
As per our discussion on the comments this would be a simple PLSQL block to do what you need. I'm doing direct from my head without test, so you may need to fix some sintaxe mistake.
BEGIN
FOR rs IN ( SELECT I_HOUSEHOLD_NUMBER,
I_PERSON_NUMBER,
I_COVIEW_DEMO_ID,
T_RESOLVED_DATE
FROM Table2 ) LOOP
UPDATE Table1
SET I_COVIEW_DEMO_ID = rs.I_COVIEW_DEMO_ID
WHERE I_PERSON_NUMBER = rs.I_PERSON_NUMBER
AND I_HOUSEHOLD_NUMBER = rs.I_HOUSEHOLD_NUMBER
AND T_RESOLVED_DATE = rs.T_RESOLVED_DATE;
END LOOP;
--commit after all updates, if there is many rows you should consider in
--making commits by blocks. Define a count and increment it whithin the for
--after some number of updates you commit and restart the counter
COMMIT;
END;

SQL pivoted table is read-only and cells can't be edited?

If I create a VIEW using this pivot table query, it isn't editable. The cells are read-only and give me the SQL2005 error: "No row was updated. The data in row 2 was not committed. Update or insert of view or function 'VIEWNAME' failed because it contains a derived or constant field."
Any ideas on how this could be solved OR is a pivot like this just never editable?
SELECT n_id,
MAX(CASE field WHEN 'fId' THEN c_metadata_value ELSE ' ' END) AS fId,
MAX(CASE field WHEN 'sID' THEN c_metadata_value ELSE ' ' END) AS sID,
MAX(CASE field WHEN 'NUMBER' THEN c_metadata_value ELSE ' ' END) AS NUMBER
FROM metadata
GROUP BY n_id
Assuming you have a unique constraint on n_id, field which means that at most one row can match you can (in theory at least) use an INSTEAD OF trigger.
This would be easier with MERGE (but that is not available until SQL Server 2008) as you need to cover UPDATES of existing data, INSERTS (Where a NULL value is set to a NON NULL one) and DELETES where a NON NULL value is set to NULL.
One thing you would need to consider here is how to cope with UPDATES that set all of the columns in a row to NULL I did this during testing the code below and was quite confused for a minute or two until I realised that this had deleted all the rows in the base table for an n_id (which meant the operation was not reversible via another UPDATE statement). This issue could be avoided by having the VIEW definition OUTER JOIN onto what ever table n_id is the PK of.
An example of the type of thing is below. You would also need to consider potential race conditions in the INSERT/DELETE code indicated and whether you need some additional locking hints in there.
CREATE TRIGGER trig
ON pivoted
INSTEAD OF UPDATE
AS
BEGIN
SET nocount ON;
DECLARE #unpivoted TABLE (
n_id INT,
field VARCHAR(10),
c_metadata_value VARCHAR(10))
INSERT INTO #unpivoted
SELECT *
FROM inserted UNPIVOT (data FOR col IN (fid, sid, NUMBER) ) AS unpvt
WHERE data IS NOT NULL
UPDATE m
SET m.c_metadata_value = u.c_metadata_value
FROM metadata m
JOIN #unpivoted u
ON u.n_id = m.n_id
AND u.c_metadata_value = m.field;
/*You need to consider race conditions below*/
DELETE FROM metadata
WHERE NOT EXISTS(SELECT *
FROM #unpivoted u
WHERE metadata.n_id = u.n_id
AND u.field = metadata.field)
INSERT INTO metadata
SELECT u.n_id,
u.field,
u.c_metadata_value
FROM #unpivoted u
WHERE NOT EXISTS (SELECT *
FROM metadata m
WHERE m.n_id = u.n_id
AND u.field = m.field)
END
You'll have to create trigger on view, because direct update is not possible:
CREATE TRIGGER TrMyViewUpdate on MyView
INSTEAD OF UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE MyTable
SET ...
FROM INSERTED...
END

Difference between "IF EXISTS" and "IF NOT EXISTS" in SQL?

I am very new to SQL. I want to know what happens when i use "IF EXISTS" or "IF NOT EXISTS".
For ex: what is the difference between the following two statements:
Statement 1: (EXISTS)
IF EXISTS( SELECT ORDER_ID FROM DBO.ORDER_DETAILS WHERE ORDER_ID = 11032 )
BEGIN
DELETE FROM DBO.ORDER_DETAILS WHERE ORDER_ID = 11032
END
Statement 2: (NOT EXISTS)
IF NOT EXISTS( SELECT ORDER_ID FROM DBO.ORDER_DETAILS WHERE ORDER_ID = 11032 )
BEGIN
DELETE FROM DBO.ORDER_DETAILS WHERE ORDER_ID = 11032
END
What will the IF EXISTS or IF NOT EXISTS return?
Which is better among these both?
When to use IF EXISTS and when to use IF NOT EXISTS
Here are 4 examples illustrating when you would use IF EXISTS and when you would use IF NOT EXISTS:
A) Delete related records from more than 1 table:
IF EXISTS (SELECT TOP(1) 1 FROM Table1 WHERE ORDER_ID = 11032) BEGIN
DELETE FROM Table1 WHERE ORDER_ID = 11032
DELETE FROM Table2 WHERE ORDER_ID = 11032
-- possibly more statements following here ...
END
B) Update record in more than 1 table if it exists:
IF EXISTS (SELECT TOP(1) 1 FROM Table1 WHERE ORDER_ID = 11032) BEGIN
UPDATE Table1 SET Field1='X' WHERE ORDER_ID = 11032
UPDATE Table2 SET Field2='Y' WHERE ORDER_ID = 11032
-- possibly more statements following here ...
END
C) Insert record in more than 1 table if it does not exist:
IF NOT EXISTS (SELECT TOP(1) 1 FROM Table1 WHERE ORDER_ID = 11032) BEGIN
INSERT INTO Table1(Field1, Field2, ORDER_ID) VALUES ('A', 'B', 11032)
INSERT INTO Table2(Field3, Field4, ORDER_ID) VALUES ('X', 'Y', 11032)
-- possibly more statements following here ...
END
D) Upsert (=insert or update) record, depending on existence:
IF EXISTS (SELECT TOP(1) 1 FROM Table1 WHERE ORDER_ID = 11032) BEGIN
UPDATE Table1 SET Field1='X' WHERE ORDER_ID = 11032
-- possibly more statements following here ...
END
ELSE BEGIN
INSERT INTO Table1(Field1, Field2, ORDER_ID) VALUES ('X', 'B', 11032)
-- possibly more statements following here ...
END
Instead of the above statement (case D), you can also use the new MERGE statement, but I think it's a bit complicated to use.
NOTES:
If there is just one table affected, you would not use EXIST in any of the examples above, except in the upsert example D).
SELECT TOP (1) 1 FROM ... is more efficient, because it aborts after the 1st match is found, then it returns just number 1 (which is more efficient to select for instance a NVARCHAR(max) field)
You can see that only in example C) you are forced to use IF NOT EXISTS(...), all other examples are using IF EXISTS(...) which is more efficient.
You need the first statement. Basically "IF EXISTS" returns true if the query return 1 or more rows, so in you example it will return a single row (containing a field with value 1) so will execute the delete statement as you desire.
Both statements will return a boolean true/false result.
EXISTS returns true if the result set IS NOT empty.
NOT EXISTS Is a negated operation, so it returns true if the result set IS empty
If there are order_details with an order_id equal to 11032, your first statement will run :
DELETE FROM DBO.ORDER_DETAILS WHERE ORDER_ID = 11032
If there are not order_details with an order_id equal to 11032, then your second statement will run. Note that this is an empty set since you just checked that there were not orders with that order_id.
It's actually going to be easier, in this example, to just run the DELETE - the IF EXISTS and IF NOT EXISTS are superfluous.
IF EXISTS checks that the result set is not empty, and IF NOT EXISTS checks that the result set is empty.
Which is better among these both?
The one that gives you the appropriate semantics.
When to use "IF EXISTS" and when to use "IF NOT EXISTS"
When you need to check the non-emptiness or emptiness of a result set.
"EXISTS simply tests whether the inner query returns any row. If it does, then the outer query proceeds. If not, the outer query does not execute, and the entire SQL statement returns nothing." See here. NOT EXISTS is the negation of EXISTS of course.
What the first statement does is that it will issue a DELETE query if the order can be found. The second one does not have any sense as it will issue the query on the ORDER when it does not exist.
This is certainly one way to use an EXISTS. I'm not sure that the second one would do anything though.
However, you could just
DELETE FROM DBO.ORDER_DETAILS WHERE ORDER_ID = 11032
and remove the EXISTS altogether, unless you wanted to perform
IF EXISTS ( SELECT ORDER_ID FROM ORDERS WHERE ORDER_ID = 11032 ) BEGIN
DELETE FROM DBO.ORDER_DETAILS WHERE ORDER_ID = 11032
DELETE FROM DBO.ORDERS WHERE ORDER_ID = 11032
END
or your actual code was more complex than what is shown.
Your second statement will never delete anything since, if there are rows, it will evaluate to FALSE and not perform the DELETE and if there are not rows, it will evaluate to TRUE and execute the DELETE which will do nothing since there are no rows.
As far as performance, in the context in which you use the EXISTS neither one has a better performance since it's really just evaluating whether the result set from the SELECT is NULL or not.
There is another use of EXISTS in which NOT EXISTS is much less efficient than EXISTS and can be effectively replaced with a better performing phrase. I'm referring to when you use NOT EXISTS in the WHERE clause of a statment. In this cause you would be better off performing a LEFT JOIN (instead of the INNER JOIN you likely have) and filter WHERE rightTable.SomeColumn IS NULL.

Check whether a table contains rows or not sql server 2005

How to Check whether a table contains rows or not sql server 2005?
For what purpose?
Quickest for an IF would be IF EXISTS (SELECT * FROM Table)...
For a result set, SELECT TOP 1 1 FROM Table returns either zero or one rows
For exactly one row with a count (0 or non-zero), SELECT COUNT(*) FROM Table
Also, you can use exists
select case when exists (select 1 from table)
then 'contains rows'
else 'doesnt contain rows'
end
or to check if there are child rows for a particular record :
select * from Table t1
where exists(
select 1 from ChildTable t2
where t1.id = t2.parentid)
or in a procedure
if exists(select 1 from table)
begin
-- do stuff
end
Like Other said you can use something like that:
IF NOT EXISTS (SELECT 1 FROM Table)
BEGIN
--Do Something
END
ELSE
BEGIN
--Do Another Thing
END
FOR the best performance, use specific column name instead of * - for example:
SELECT TOP 1 <columnName>
FROM <tableName>
This is optimal because, instead of returning the whole list of columns, it is returning just one. That can save some time.
Also, returning just first row if there are any values, makes it even faster. Actually you got just one value as the result - if there are any rows, or no value if there is no rows.
If you use the table in distributed manner, which is most probably the case, than transporting just one value from the server to the client is much faster.
You also should choose wisely among all the columns to get data from a column which can take as less resource as possible.
Can't you just count the rows using select count(*) from table (or an indexed column instead of * if speed is important)?
If not then maybe this article can point you in the right direction.
Fast:
SELECT TOP (1) CASE
WHEN **NOT_NULL_COLUMN** IS NULL
THEN 'empty table'
ELSE 'not empty table'
END AS info
FROM **TABLE_NAME**