how to update the selected rows in same query? - c#

I have 1 table table1, and a select query
select col1 from table1 where id <= 10;
I want to update the same records
update table1 set col2 = 'some value' where id < 10;
I want to do both the operations in 1 query and get the selected result also so that i can use it.
How can I do that?

You can not update and select row using one single query, since both are different operation.
So you need to write 2 different queries.
If you don't need to update table and want temporary output, then #Yosi had provided you with perfect solution.

You don't have to update it, you an use CASE statement:
SELECT col2 = CASE WHEN id<=10 THEN 'some value' ELSE col1 END
FROM table1

Try this sql query using OUTPUT to get the updated vlaue
UPDATE persons
SET LastName = 'test'
OUTPUT Inserted.LastName
where id<10;
If you need the old value after updation:
UPDATE persons
SET LastName = 'test'
OUTPUT DELETED.LastName
where id<10;
DEMO

Related

Create an id autoincrement with dapper

I'm working with Dapper and .Net 6.0... I have to do an insert from table1 to table2... in the insert the columns match each other... the only column is "toID" of table1... which does NOT match the column of table2 (that's why I put a 4 in it) but I have to make it auto-increment so that for each insert there is an incrementing sequence
var sql =
$"INSERT INTO table1 (toId,teId,dateShift,SectorOrigen) SELECT 4,teID,#dateModify,#LastSector FROM table2";
That is to say... that when I generate an insert the ID = 1, then another ID = 2 and so on continuously
Any advice??
You can create and use the sequence https://learn.microsoft.com/en-us/sql/t-sql/statements/create-sequence-transact-sql?view=sql-server-ver16

For loop for array which should have If condtion c#

I have to iterate a array with for loop to find it contains specific words in it and add that in listbox
String[] result= ["vicky","vinay#","google#","hello"]
For (l=0 ; l<= result.length; l++)
{
If(result[l].contains("#")
{
Listbox.items.add(result[l]);
}
}
What this does is it gets only first found value I am not getting second value?
You need an ordering column for your data. Let me assume that you have one.
First add the new column:
alter table t add column id int;
Note: id is a really bad name for a column that can be null. Then:
with toupdate as (
select t.*,
row_number() over (partition by col1 order by <ordering col>) as seqnum
from t
)
update toupdate
set id = (case when col1 = 1 then seqnum end);
Strictly speaking, you don't need to update the values when col1 = 0, because the default value is NULL. However, in case you want a different value there, I am leaving out the where col1 = 1.
You can simulate a partial identity column, but you won't be able to incorporate an actual IDENTITY column to the table that works conditionally.
If you just need to update a new column with an incremental value, you can just use a ROW_NUMBER() over a filtered SELECT:
;WITH CTE AS
(
SELECT
T.Col1,
T.ID,
GeneratedID = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -- Determine your order here
FROM
YourTable AS T
WHERE
T.Col1 IS NOT NULL
)
UPDATE C SET
ID = C.GeneratedID
FROM
CTE AS C
Your query should be like below :
update <table_name> set id=1 where Col1=1;
update <table_name> set id=null where Col1=0;

Returning data which is not found in where clause and didn't update in sql

In a c# desktop application I am getting this list of data which I am reading by barcode into text file; here is the result;
R900, 27674T07, 27438T17, 27736T21, 26609T08,
R901, 27770T12, 27833T07, 26402T12, 27771T09, 26003T13,
R902, 26003T14, 26402T11, 26246T17,
R904, 28055T09, 25356T08, 25825T07, 25556T09,
and I am transforming it to update queries;
UPDATE TABLE SET NUMBER = R900 WHERE id in ( 27674T07, 27438T17, 27736T21, 26609T08)
UPDATE TABLE SET NUMBER = R901 WHERE id in ( 27770T12, 27833T07, **26402T12**, **27771T09**, 26003T13)
UPDATE TABLE SET NUMBER = R902 WHERE id in ( 26003T14, **26402T11**, 26246T17)
UPDATE TABLE SET NUMBER = R904 WHERE id in ( 28055T09, 25356T08, 25825T07, **25556T09**)
Finally I am executing this SQL query. But the problem is I don't know which id is not found in IN clause in database. I need to report back to user which id didn't found with its NUMBER
For example the bold id's are not found in database, and couldn't update. So expected result is:
NUMBER id
R901 26402T12
R901 27771T09
R902 26402T11
R903 25556T09
how can I return this?
You could do something like this
declare #mytable as TABLE
(
Id nvarchar(20)
)
UPDATE TABLE SET NUMBER = R900
OUTPUT INSERTED.Id into #mytable
WHERE id in ( 27674T07, 27438T17, 27736T21, 26609T08)
Select * from #mytable
#mytable will contain updated Ids only.
Hope this helps.
create a temp table to store the splitted value into it.
then
SELECT temp.number, temp.Id
FROM #temp temp
LEFT OUTER JOIN TABLE ON temp.id = TABLE.id
WHERE TABLE.id is null

While Selecting based on ROWID - Distinct or Group By doesn't work in oracle

I have query like below , I tried to filter out duplicate columns by using Group BY
SELECT contacts.rowid AS ROW_PASS,
duty_rota.rowid AS ROW_PASS_ROTA,
duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
GROUP BY contacts.rowid,
duty_rota.rowid,
duty_rota.duty_type
ORDER BY duty_date
After playing with the query little bit I came to know we can't filter out distinct using group by while using ROWID. So can somebody please help me to write code (in SQL) with a logic that
if (any row is completely identical with another row of the query o/p)
{
then display only one column
}
I will be using the output as gridview's data source in C#, so if not in SQL - can you help me whether somehow in C# I can achieve to display only identical columns?
If you want to filter duplicate rows, you can use this query:
SELECT Max(duty_rota.rowid) AS ROW_PASS_ROTA,
duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
GROUP BY duty_rota.duty_type
ORDER BY DUTY_TYPE
Here you go: http://sqlfiddle.com/#!2/2a038/2
Take out the ROWID's. Example: If your table has 3 columns (colA, colB, colC) you could find exact row dups this way...
select a.* from
(
select count(*) dupCnt, colA, colB, colC from myTable
group by colA, colB, colC
) a
where dupCnt > 1
First, the ROWID is a unique field for each row, so using this field you will never have duplicates. The only solution here is to not use it. It's data does not hold anything you would want to display anyway.
Simply put, if you want no duplicates, you need the DISTINCT keyword:
SELECT DISTINCT field1,
field2
FROM table1,
table2
WHERE table1.key1 = table2.key1;
This will select all Field1, Field2 combinations from the two tables. Due to the DISTINCT keyword, each line will only be in the result list once. Duplicates will not be in the result list.
SELECT DISTINCT duty_rota.duty_type AS DUTY_TYPE
FROM duty_rota,
duty_types,
contacts
WHERE duty_rota.duty_type = duty_types.duty_type
AND duty_rota.duty_officer = contacts.duty_id
AND sname IS NOT NULL
ORDER BY duty_date
You will only need to GROUP BY if you need further operations on the result set, like counting the duplicates. If all you need is "no duplicates", the DISTINCT keyword is exactly what you are looking for.
Edit:
In case I misread your question and you want to see only those, that are duplicates, you need to group and you need to filter based on the groups criteria. You can do that using the HAVING clause. It's kind of an additional WHERE of the groups criteria:
SELECT FIELD1, FIELD2, COUNT(*)
FROM TABLE1, TABLE2
WHERE TABLE1.KEY1 = TABLE2.KEY1
GROUPB BY FIELD1, FIELD2
HAVING COUNT(*) > 1

SQL: Update a row and returning a column value with 1 query

I need to update a row in a table, and get a column value from it. I can do this with
UPDATE Items SET Clicks = Clicks + 1 WHERE Id = #Id;
SELECT Name FROM Items WHERE Id = #Id
This generates 2 plans/accesses to the table. Is possibile in T-SQL to modify the UPDATE statement in order to update and return the Name column with 1 plan/access only?
I'm using C#, ADO.NET ExecuteScalar() or ExecuteReader() methods.
You want the OUTPUT clause
UPDATE Items SET Clicks = Clicks + 1
OUTPUT INSERTED.Name
WHERE Id = #Id
Accesses table only once :
DECLARE #Name varchar(MAX);
UPDATE Items SET Clicks = Clicks + 1 , #Name = Name WHERE Id = #Id;
SELECT #Name;
If you're using SQL Server 2005 onwards, the OUTPUT clause is ideal for this
Use a Stored procedure for this.
Create a stored procedure that takes the #id as a parameter and does both of those things. You then use a DbDataAdapter to call the stored procedure.
I could not manage to update and return one row inside a select statement. I.e you can not use the selected value from the other answers.
In my case, I wanted to use the selected value in a query. The solution I came up with was:
declare #NextId int
set #NextId = (select Setting from Settings where key = 'NextId')
select #NextId + ROW_NUMBER() over (order by SomeColumnOfYourTable) from YourTable
update Settings set Setting = Setting + ##ROWCOUNT
where key = 'NextId'

Categories

Resources