insert into related tables in same time - sql

I'm working on vb.net project. I'm using VS2010 and SQL Server 2008.
I have many tables in my database, amongst them members and bank.
members contains columns: id_member, name, mobile, tel
bank contains id_bank, name_bank
Then I created member_bank table with 2 columns: members.id and bank_id for the m:n relationship between those two tables.
How can I insert details into members and join member id directly with bank id in the member_bank table ?
I wrote this code put it doesn't work:
Dim saveok As Boolean = wnclass14.SQLExicute("Insert Into members (member_name,member_id,mobile,tel) values ('" & TextstdntName.Text & "','" & Textid.Text & "','" & TextMobile.Text & "','" & Texttel.Text & "')")
If saveok = True Then
Dim saveok1 As Boolean = wnclass14.SQLExicute("Insert Into member_bank (id_member,id_bank) values (" & ComboBoxBank.SelectedValue & ") where member_bank.id_member=members.id")
If saveok1 = True Then .......

Part of the trick here is that you kind of want all of these to take place as part of a single transaction. Thankfully, it's not that hard to do this by sending multiple statements in a single call to your "SQLExicute" function (fix your spelling please):
wnclass14.SQLExicute( _
"BEGIN TRANSACTION;" & _
"DECLARE #NewID Int;" & _
"INSERT INTO members (member_name, mobile, tel) " & _
" VALUES ('..', '555-1234', '555-5678');" & _
"SELECT #NewID = Scope_Identity();" & _
"INSERT INTO member_bank (id_member, id_bank) " & _
" VALUES (#NewID, '1234');" & _
"COMMIT;)
And while we're here, you really need to fix this function so that it's also asking for parameter data.
It is not okay to to use string concatenation to include user-entered data in your sql statements.
It is not okay to skip this because you're still learning. And
it is not okay to "just get it working" first and then go back and fix the security issues afterwards

I assume you want to return the memberid from the members table after you do an insert? If so, you need to look into SCOPE_IDENTITY(). This should return the last Identity that was inserted into the table for your scope.
Here is a good article:
http://msdn.microsoft.com/en-us/library/ms190315.aspx
I'd supply code, but I don't really understand yours.
Good luck.

Related

Run-time error 3134 "Syntax error in INSERT INTO statement"

I am for the first time posting question in this platform. Currently, I am running into a problem of executing my assignment of online shopping database. When I try to register an account into it, it always pops up a window say run-time 3134 error, syntax error in INSERT INTO statement. I was trying any possibilities in order to solve the problem but it won't work. So, any solution to counter this problem? Thanks for your many helping. 😊
Here is my codes:
CurrentDb.Execute "INSERT INTO Login table (FirstName,LastName,Gender,UserName,Password,Email,Phone) VALUES ('" & Me.FirstName & "','" & Me.LastName & "','" & Me.Gender & "','" & Me.UserName & "', '" &
Me.Password & "','" & Me.Email & "','" & Me.Phone & "')"
Presuming that the table you're trying to INSERT INTO is named Login Table, you have a space in the table name, which means any time you reference that table you need to surround it in square brackets.
CurrentDb.Execute "INSERT INTO [Login table]` (FirstName,LastName,Gender,UserName,Password,Email,Phone) VALUES ('" & Me.FirstName & "','" & Me.LastName & "','" & Me.Gender & "','" & Me.UserName & "', '" &
Me.Password & "','" & Me.Email & "','" & Me.Phone & "')"
This is one of the main problems with naming your table with spaces. Also, Login table is an especially bad name - you already know it's a table, so why do you need to repeat that information in the table name? And if you insist on using table names that are more than one word, you should use an underscore rather tha a space (like Login_table) to reduce the work involved with every query and prevent problems like the one you're having here.
Consider using a stored query that points to the form controls as parameters and avoid VBA variable concatenation and quote punctuation. Also, query design in Access GUI does not allow users to save query with syntax errors.
SQL
Adjust myForm to actual form name.
INSERT INTO [Login table]
(FirstName,
LastName,
Gender,
UserName,
Password,
Email,
Phone)
VALUES
(Forms!myForm!FirstName,
Forms!myForm!LastName,
Forms!myForm!Gender,
Forms!myForm!UserName,
Forms!myForm!Password,
Forms!myForm!Email,
Forms!myForm!Phone)
VBA
No need to close action queries and add SetWarnings to avoid update prompts.
DoCmd.SetWarnings False
DoCmd.OpenQuery "mySavedAppendQuery"
DoCmd.SetWarnings True
Password is a reserved word, so:
CurrentDb.Execute "INSERT INTO [Login table] (FirstName,LastName,Gender,UserName,[Password],Email,Phone) ...
I have just found that the the table had a field that was using a reserved name Note. By placing it in `` quotes (Note) fixed the issue.

Getting an error inserting a user variable into a table with Visual Basic

I've been trying to insert a new entry into a table, but I'm having problem inserting the current date. For context, I'm using Visual Studio with the Visual Basic language. The method that I have in the data access object is this one:
Public Function InsertPlayback(ByVal u As User, ByVal s As Song, plDate As Date) As Integer
Return DBBroker.GetBroker.Change("INSERT INTO PLAYBACKS (user, song, plDate) VALUES ('" & u.Email & "', " & s.idSong & ", '" & Date.Today.ToString & "');")
End Function
And the error that I'm having is "Syntax error in INSERT INTO statement". It is really weird, since I'm trying this same SQL sentence in Access where I have stored the database and it is giving me what it should without any errors. Does anyone know what is happening? Do I have to install or configure something?
Solution
Thanks to Nathan_Sav, I manage to solve the problem. The real problem was that the user word is a reserved keyword, so we need to put the variable "user" between brackets [] so that the server recognizes it as an ordinary variable. I'm also changing the title of this post since it is misleading.
So, in conclusion, the result would be:
Public Function InsertPlayback(ByVal u As User, ByVal s As Song, plDate As Date) As Integer
Return DBBroker.GetBroker.Change("INSERT INTO PLAYBACKS ([user], song, plDate) VALUES ('" & u.Email & "', " & s.idSong & ", '" & Date.Today.ToString & "');")
End Function

Creating Receipt Id for each Transaction

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

Searching a table where the field doesnt exist - Access VBA

I am a data consultant who migrates data I am sent into our system. I have written code that compares the contents of my table against what has been put into oracle, as an extra test. The tables are a little convoluted due to how they relate to each other. But essentially here is my question:
When I look to match two field values and the field doesnt exist I get a parameter pop up box. I want to only run the code if the field exists.
I have tried many things, wrapping an if statement around it but I always get the parameter box, can anyone help there must be an easier way to do this!
If Not DoCmd.OpenQuery("SELECT TOP 1" & MatchValues!FieldName & " FROM " &
MatchValues!ORACLE_TABLE_NAME) Then
MsgBox "moomins"
' strSQL = "INSERT INTO 002_TableValueErrors(ORACLE_TABLE_NAME,TRANSFORM_TABLE_NAME,FIELD_NAME,ORACLE_FIELD_VALUE,TRANSFORM_FIELD_VALUE) "
' strSQL = strSQL & " VALUES (" & MatchValues!ORACLE_TABLE_NAME & "," & MatchValues!TRANSFORM_TABLE_NAME & "," & MatchValues!FieldName & ",'ORACLE: NOT FOUND','ORACLE: NOT FOUND')"
End If
If you deal with Oracle: Have you tried to check if the field exists by querying ALL_TAB_COLUMNS in Oracle?
"Select count(*) from ALL_TAB_COLUMNS where table_name = " & MatchValues!ORACLE_TABLE_NAME & " and COLUMN_NAME = " & MatchValues!FieldName
(Untestet cause currently I have no Oracle Instance available)

T-SQL - Filtering records based on a date

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;