I have an update statement and i wanted to know how i could get the primary key of the row i just updated.
SELECT ##identity
I tried this but it didn't work.
I keep on getting 0.
But my update statement could be the problem aswell because in not sure about it either.
UPDATE payment INNER JOIN booking SET hire_cost=" & cost(1) & ",additional_cost=" & cost(0) & ",total_cost=" & cost(2) & ",Deposit=" & Math.Round(cost(2) / 4) & " WHERE booking.bookingID='" & y & "' AND payment.PaymentID=booking.PaymentID
Please help!
You will need to specify your column in the database as an identity column for it to return anything other than 0
Related
Background
I am using an Excel UI and VB ADODB back-end so users can insert data into SQL Server.
Since users are free to use as many rows as they would like (business requirement), I ended up using a FOR loop to iterate through the rows and insert them one by one.
Initial Code
For i = 7 To LastRow
Command.CommandText = "INSERT INTO [dbo].[TEP_Payments_Table] ([AA Number], " & _
"[AA Name], [Request Receipt Id])" & _
"VALUES (" & _
"'" & Sheets("Project_Name").Cells(i, 2).Value & "'," & _
"'" & Sheets("Project_Name").Cells(i, 3).Value & "'," & _
"'" & Sheets("Project_Name").Cells(i, 6).Value & "')"
Command.Execute
The 'Request Receipt Id' column is filled by Col6 in 'Project_Name' sheet. That was auto filled by by looking at the last id in TEP_Payments_Table and +1.
This resulted in duplicates if multiple users use it simultaneously.
I managed to get workout how to user OUTPUT INSERTED in a standard INSERT INTO clause to generate an id for each transaction; using the following syntax:
declare #ids table (id int);
insert into [dbo].[TEP_Payments_Table] ([col1], [col2])
output inserted.id into #ids
values ('testval1', 'testval2');
Problem
I am reluctant to add the declare and output inserted into the for loop, because I do not want it to do it for every line. I want a single id to be generated whether a user inserts 1 row of data, or 100 rows of data.
This is important as this receipt id will be used to track status of request.
Any ideas how to solve this problem?
Thanks
I'm fairly new to access but not to vba. I have a form that inserts data to a table with vba
rcrdAdd = "INSERT INTO " & timeTbl & " (ProjectNumber, AssignedTo, Task, taskStart) VALUES ('" & ProjectNumber.Value & "', '" & combobox.value & "', '" & combobox.value & "', '" & datetime.value & "');"
db.Execute rcrdAdd, dbFailOnError
When i run this it does add the record but it also updates the first record in the table with the project number associated with record it just added.
I don't know what or why. Can anyone shed any light here. I have tried to research why and can not find an answer
Your form is bound to a the table's recordsource and it looks like you've created a project number text box that is bound to the field
Then it looks like you're typing in the new project number (ProjectNumber.Value) for the Insert.
That will automatically update the current record when you leave - most likely you're opening the form to the first record in the table
Just create a new TEXTBOX that is UNBOUND - and use that in your INSERT INTO SQL instead of ProjectNumber.Value
I've done lots of research, read lots of posts, and I found none using edmx (Entity Data Model) with EF6.
Here is my problem:
Simple table...
CREATE TABLE Oops (
OopsID INTEGER NOT NULL
PRIMARY KEY AUTOINCREMENT,
UserID INTEGER NOT NULL
REFERENCES Users (UserID),
Reason VARCHAR (100) NOT NULL
);
I am trying to retrieve the last OopsID inserted.
In VB.Net I have tried the following:
Dim dbContext As New RCA.Entities
' Always returns 1
Dim rtnVal1 As Int64 = dbContext.Database.ExecuteSqlCommand("INSERT INTO Oops (UserID,Reason) VALUES(" & clsShared.iUserID & ",'" & txtReason.Text & "'); SELECT last_insert_rowid() FROM Oops;")
' Always returns -1
Dim rtnVal2 = dbContext.Database.ExecuteSqlCommand("INSERT INTO Oops (UserID,Reason) VALUES(" & clsShared.iUserID & ",'" & txtReason.Text & "'); SELECT SEQ from sqlite_sequence WHERE name='Oops';")
However the following query in SQLiteStudio return 7, the correct value:
SELECT SEQ from sqlite_sequence WHERE name='Oops'
It seems as if the 2 commands in one statement would be processed on different connections, which I doubt.
Any help appreciated.
This code finally worked for me:
Using dbContextTransaction = dbContext.Database.BeginTransaction()
Try
dbContext.Database.ExecuteSqlCommand("INSERT INTO Oops (UserID,Reason) VALUES(" & clsShared.iUserID & ",'" & txtReason.Text & "')")
Dim rtnVal = dbContext.Database.SqlQuery(Of Int64)("SELECT last_insert_rowid();").ToList
dbContextTransaction.Commit()
Catch generatedExceptionName As Exception
dbContextTransaction.Rollback()
End Try
End Using
An FYI, the value "1" I was originally getting from ExecuteSqlCommand was the number of rows affected.
you should write
SELECT SCOPE_IDENTITY()
to get last inserted id
I know there's a way to have insert statements within excel. Is there one for update? so far I've managed to come up with my update statement in SQL, but I have 6000 rows to update:
= "Update table Set name = " & A1 & " Where namefk = " & E2 & ""
Basically, I want the name and namefk to be populated with fields in my excel..but I can't seem to get it right. Any help will be appreciated.
= "update table set name = '" & B1 & "' where namefk = '" & A1 & "'"
where column A1 has name fk & B1 have name
You can drag the formula to achieve query to update thousands of records :)
You can look into the link with the
Example excel
Hope it helps
=CONCATENATE("update Site set SiteName='",D13,"' where Place='",A13,"' and Code='",B13,"'")
As per above we can make update query dynamically and if we make for one row after that we need to drag down, so automatically it will take column values.
I am writing SQL Server queries and need a solution for how to filter the rows that are returned properly.
The basic setup is as follows - I am selecting a bunch of records from a table based primarily on an identifier. So, for a given identifier there might be 100 records that are returned initially. Within these 100 records, however, there are a number of them that need to be deleted - not because they are duplicates, but because one is newer than the other. So I essentially just need a way to further filter the results based on whichever record was created/modified most recently.
I know that ideally, these "old" records should not be in the database, but I don't have control over that. What is happening is essentially people are updating the entries over time to reflect new information, but rather than editing the "old" entry, a new one gets entered each time. Thus, there might be 3 entries for a given identifier, but I only need the one that was most recently entered.
Is there an easy way to do this in the T-SQL query string? It would be similar to the "Last of" function in Access queries. I do have a properly formatted date column for each record.
Thanks!
My query string so far (excuse the VB syntax):
"SELECT *" & _
"FROM Performance_Override " & _
"WHERE ([Deal_Name] = " & "'" & Range("ID").value & "'" & " or" & _
" [UNIQUE_ID] LIKE " & "'" & "%SPLIT_LOAN%" & "')" & " AND" & _
" ([Scenario] = " & "'" & "BASE" & "')" & _
"ORDER BY [Date] ASC; "
Select is
select ID, max(datefield)
from table
group by ID
Do you just need a select or do you want to actually delete the old entries?
WITH TableTop AS
(
SELECT ID, User, OrderDate
ROW_NUMBER() OVER (ID BY OrderDate DESC) AS RowNumber
FROM Table
)
SELECT ID, User, OrderDate
FROM TableTop
WHERE RowNumber = 1;