Is it possible to add a number to a unknown number in sql column? For example:
In my sql database is a column named "overallRating". I want to add +1 to whatever number is stored in that column. So if number 14 is stored in overallRating column, +1 would make it 15.
Is this possible to do this without retreving this number from sql first? Something like:
UPDATE MyTable SET overallRating+=1 WHERE url='myurl..'
EDIT When solution was already given:
Actually I haven't tried my code above, but I did now and it also works. I made a syntax error on my first try, that's why I thought it's not working.
The += syntax is very new to T-SQL and generally not supported by most PROD systems today and so you just need to spell it out:
UPDATE MyTable SET overallRating=overallRating+1 WHERE ...
It will work like
update users set userid = (userid + 1) where userid = 1
Related
I am working on a desktop application in C#. I am very new to SQL Server.
First of all I would like apologize for the question I am asking may be relevant to the questions asked before on this topic, but I searched on the internet and did not find any answer for the problem.
There is a table in my database named BillingTemp. Columns are
Bill No, Package, Type, DiscPer, TotalAmt, BillDate, TaxAmt
BillNo may repeat as there are multiple entries in a specific bill.
Now on a button click, TotalAmt and type values in this table should be updated in only first row of a table as per my logic in the code.
How can I do this? Can anyone suggest query for this?
Try this
;WITH TOP1 AS
(
SELECT TOP 1 *
FROM TABLE
WHERE BillNo = #BillNo
ORDER BY ID -- I assume you always want to update the record created first
)
UPDATE TOP1 SET TotalAmt =#TotalAmt , type = #type
I have multiple tables in my SQL Server database.
I have one table [Tatkal_Merge] which has fields like filename,C_srno,Scan,etc. [c_srno is the secondary key]
The second table Collation_Data has details like srno,filename, dispatchcount, totalcount etc. [srno is the primary key]
The totalcount is the total number of records in tatkalmerge table.
There are many other fields in both tables but not relevant to this question.
Whenever the customer scans a barcode in winForm and the update is successful I update [Tatkal_Merge] with scan value 'Y' and increment the Collation_Data dispatch count using stored procedure
update [Tatkal_Merge] set [DScan]=#scan,[DScanBy]=#scanBy,[DScanTime]=getdate() where Dscan='N' and [wl_barcode]=#wl
if(##ROWCOUNT=1)
update Collation_Data set Dqty=Dqty+1 where srno=#C_srno
Issue
Sometimes due to some reason the Dispatch count is not correct by 1 or 2 customers.
Requirement:
1) Please guide why there is a discrepancy in the count. My guess is network issue between first and second command.
2) If am doing it the wrong what is the correct way of doing this?
3) If am doing it the right how to update the Table B in such scenario?
P.S.
Currently, I am updating the collation_Data using correlated subquery periodically,
update Collation_Data c
set Dqty = (select count(*)
from [Tatkal].[dbo].[Tatkal_Merge] m
where m.Dscan = 'Y' and m.collation_code = c.collation_code
);
Few things you can do to isolate and troubleshoot:
Enclose both updates inside a transaction
Trap the ##ROWCOUNT on second update and if that is = 0 it means that the update wasnt succesfull and you could write all the important fields and variables into a logging table that might lead you to the culprit.
The main reason why the second update would fail would be if the ##ROWCOUNT from the first update was <> 1 or if it didnt find any row for that srno. Unlikely that it is a network issue.
if(##ROWCOUNT=1)
this might be an issue if there are more matching rows to the first update of table [Tatkal_Merge]. Instead change it to:
if(##ROWCOUNT > 0)
update Collation_Data set Dqty=Dqty+1 where srno=#C_srno
I'm using EF in order to insert and retrieve info from DB,
there is any way to insert new row but at the specified position,
Like i have 10 rows with IDs ranging from 0 to 9 and new row i'm inserting will be on the position 4?
I'm using ASP.NET MVC 5 and LINQ.
Thank you.
The simple answer is no. Order has no meaning unless it's explicit in a database system. Sure in most cases I can insert into a table and pull from this exact table and get the exact order as it was inserted, but this is undefined...and the only guarantee is to use an ORDER BY clause.
If you are talking about changing an auto number property, this is also not possible, the database does not go back and fill in gaps with id numbers. If numbering is critical and important to you don't set the auto-increment property.
Your ID and order position are different things.
For ID you use an autonumeric and you shouldnt mess with that.
For order you use another column and run a trigger when a new row is insert update all the rows
So when the new row is inserted with order_id = 4 all the rows get update
something like
UPDATE table
set order_id = order_id +1
when order_id >= 4
So, I would do so quickly:
I would plan the database to not auto increment primary key and saving would so that the id is attributed according to the specific location. Obviously put an IF to verify that it is available, and if I would start a review cycle to the cascade of subsequent ID or positioning the value traded in the end.
for example
MyTable table = myDb.MyTable.Find(id); //position
if (table==null)
{ table.id=position; table.Field=value; myDb.SaveChanges() }
else
{
var temp = table.id;
var max = table.count(x=> x.id).value;
table.id=max+1;myDb.SaveChanges();
table.id=id; table.Field=value; myDb.SaveChanges();
}
sorry if translate is no good! ;-)
I have created table in MS SQL 2008 with one identity column(Start Value - 1 and Increment is also 1) and 4 other columns. I am accessing this DB from C# ASP.NET. Used to push data only for the non identity column. Identity column will auto increment itself.
As of now i am manually querying the column value with the remaining for columns. But I am facing problem if all the other four column values are equal i am not getting the exact value which i am looking for
Now my query is, Is there any why in C# where I can get the value of the newly created identity column whenever new record is created.
Thanks.
You can use
SCOPE_IDENTITY()
Which will returns the primary key value of the recently inserted row
The answer to your question actually lies in SQL Server. You can run:
SELECT ##identity
after your insert to get the last inserted row identity.
http://technet.microsoft.com/en-us/library/aa933167(v=sql.80).aspx
EDIT BASED ON COMMENTS:
Consider using SCOPE_IDENTITY() as referenced here:
http://technet.microsoft.com/en-us/library/aa259185(v=sql.80).aspx
In SQL terms you can output the records back if you wish it. But how you might apply this to C# is up to you. Example:
INSERT INTO TABLE_A (SOMETHING, SOMETHINGELSE, RANDOMVAL3)
OUTPUT inserted.A_ID, inserted.SOMETHING, inserted.SOMETHINGELSE, inserted.RANDOMVAL3
SELECT 'ASD','DOSD', 123
But unless you're using merge, you can't use OUTPUT to print out any values from joining tables from an INSERT. But that's another matter entirely, I think.
Also, it's hardly good practice to bounce this data between the application and the DB all the time, so I'd look to alternatives if possible.
Hello I have a simple question that regards inserting data into a MS MySql Database 2012 table. The table that I have is called COMPLETED and has 3 fields.
student_ID (int, NOT allowed nulls)
completed (bool, NOT allowed nulls)
random_code (string, allowed nulls)
In c# I have a list filled with unique random codes. I want all codes inserted into the database, so if I have 20 records I want 20 unique codes inserted into the random_code field. So the first records gets the first code, the seconds records gets the second code and so on. I think the best way to do this is using a foreach and, for each code in the list of codes insert that code into the random_code field in my database. The problem is I don't know how to do this. I have the following code that give's me an error at VALUE:
Incorrect syntax near 'VALUE'.
foreach (string unRaCo in codes)
{
//insert database
SqlCommand toDB = new SqlCommand("INSERT INTO COMPLETED (random_code) VALUE ( '"+ unRaCo +"' ) ", conn);
SqlDataReader toDBR;
toDBR = toDB.ExecuteReader();
}
Could anyone give me a dircetion here? Thanks in advance.
EDIT:
Okay I totally changed my query as I figured out it did not yet do what I wanted it to do. I now want to update my records instead of inserting records. I did that with the following code:
foreach (string unRaCo in codes)
{
//insert database
SqlCommand naarDB = new SqlCommand("UPDATE VOLTOOID SET random_code = '"+ unRaCo +"' ", connectie);
SqlDataReader naarDBR;
naarDBR = naarDB.ExecuteReader();
naarDBR.Close();
}
The problem this time is that the update query updates ALL records with the first code, so the first record has the code 12345 for example but all other records also have that code. I want to update 12345 into record 1 and 54321 for example in number 2, how do I do that?
The correct is Values not Value, even if you only provide one column.
About your edit. First of all beware of SQL Injection. You better use SQLParameter class. Check Configuring Parameters and Parameter Data Types for further info.
If you want to update a specific id then use a where clause like (in plain SQL):
UPDATE VOLTOOID SET random_code = #NewValue WHERE random_code = #OldValue
Now if you just want to add the random number in a specific row, then you would have to use some more advanced SQL functions. Again in plain SQL you would have:
;WITH MyCTE AS
(
SELECT random_code,
ROW_NUMBER() OVER(ORDER BY random_code) AS ROWSEQ -- This will give a unique row number to each row of your table
FROM VOLTOOID _code
)
UPDATE MyCTE
SET random_code = #NewValue
WHERE ROWSEQ = #YourRandomRow
As the above queries are for SQL script execution you will need to define the variable used.
Your syntax is wrong, you are using 'value' where you should use 'values'. If you have SSMS you will able to easily figure out this kind of errors.
Usually I create the query in SQL Server Management Studio query editor, then use it in C#. Most of the times I use SQL Server stored procedures where it's possible. Because I think it cost some extra resources to execute a text query than executing a procedure