I have encounter a problem where it tell me I have an Invalid SQL statement; expected 'DELETE','INSERT','PROCEDURE', 'SELECT', or 'UPDATE'.
I am trying to insert data that use foreign key.
Table pemain contain
ID
MABOPA
PKBM
MBA
MBEIA
PPPBBM
MAPIM
Table Ahli contain
ID
company_name
name
address
poscode
state
email
phone
fax
company_reg
website
remarks
pemain
where field pemain in table Ahli is the foreign key of table pemain
the code im using are
Dim Pos As Integer
Dim Pemain As Integer
Int32.TryParse(TxtBoxPoscode.Text, Pos)
Int32.TryParse(TxtBoxPemainId.Text, Pemain)
Access.AddParam("#MABOPA", TextBox1.Text)
Access.AddParam("#PKBM", TextBox2.Text)
Access.AddParam("#MBA", TextBox3.Text)
Access.AddParam("#MBEIA", TextBox4.Text)
Access.AddParam("#PPPBBM", TextBox5.Text)
Access.AddParam("#MAPIM", TextBox6.Text)
Access.AddParam("#companyname", TxtBoxComName.Text)
Access.AddParam("#name", TxtBoxName.Text)
Access.AddParam("#address", TxtBoxAdd.Text)
Access.AddParam("#poscode", Pos)
Access.AddParam("#state", CboBoxState.Text)
Access.AddParam("#email", TxtBoxEmail.Text)
Access.AddParam("#phone", TxtBoxPhone.Text)
Access.AddParam("#fax", TxtBoxFax.Text)
Access.AddParam("#companyreg", TxtBoxComName.Text)
Access.AddParam("#web", TxtBoxWebsite.Text)
Access.AddParam("#remarks", TxtBoxRemarks.Text)
Access.AddParam("#pemain", Pemain)
'Execute Insert Command
Access.ExecQuery(
"START TRANSACTION;" & _
"INSERT INTO pemain (MABOPA, PKBM, MBA, MBEIA, PPPBBM, MAPIM);" & _
"VALUES (#MABOPA, #PKBM, #MBA, #MBEIA, #PPPBBM, #MAPIM);" & _
"DECLARE #NewID INT;" & _
"SELECT #NewID = SCOPE_IDENTITY();" & _
"INSERT INTO Ahli (company_name, name, address, poscode, state, email, phone, fax, company_reg, website, remarks, pemain);" & _
"VALUES (#companyname, #name, #address, #poscode, #state, #email, #phone, #fax, #companyreg, #web, #remarks, #NewID);" & _
"COMMIT;")
It would be a really great if anyone could help me.
Neither the Jet nor ACE OLE DB providers support multiple SQL statements per command. If you want to execute multiple SQL statements then you must execute multiple commands (or the same command more than once with different SQL statements) and if you want to wrap them in a transaction then you call BeginTransaction on your OleDbConnection to create an OleDbTransaction.
By the way, I'm not sure that SCOPE_IDENTITY exists in Access. I could be wrong but I think that that's specific to SQL Server. I think Access requires using ##IDENTITY.
Related
I have the following code:
Private Sub Command134_Click()
Dim strInsert As String
Set db = CurrentDb()
strInsert = "INSERT INTO [SEMP Documentation] (Staff_Name) VALUES " & (Staff_Name.Value) & ");"
MsgBox (strInsert)
Debug.Print staffname
db.Execute staffname, dbFailOnError
End Sub
Staff_Name is a combo box on a Microsoft Access form that has the name of 10 or so individuals, each with their own index.
The message box has the Staff_Name.Value call producing the index rather than the actual text name. For reference, the values in the combo box are pulled from a table, where the first column is the staff's index and the second column is the staff's name.
The user picks which person they are.
Secondly, the db.Execute statement fails; the table name is SEMP documentation that I am trying to insert into - "The Microsoft Access database engine cannot find the input table "
any help appeciated
try this
"INSERT INTO [SEMP Documentation] (Staff_Name) VALUES ('" & (Staff_Name.Value) & "');"
2nd prob is
db.Execute staffname, dbFailOnError
should be db.Execute strInsert, dbFailOnError
I am currently making a project for school where I have to make a program where I can create orders in.
When I try to create orders I get this error returned to me.
Error converting Data Type Nvarchar to Int.
In advance I'm sorry if this is a really basic question that is easely spotted. Me and my project members are beginning programmers but we simply cannot spot where this goes wrong.
The code we execute in vba is this :
Set rs = DbConn.Execute("EXEC spOrderPlaatsen '" & Me.tbTijd & "', " & Me.klantnr & ", '" & Me.tbOphaaldatum & "', '" & Me.tbAfleverdatum & "', '" & Me.tbOphaaladres & "', " & Me.tbPalletnr & ", " & Me.tbAantalpallets & "")
This code execute's our Stored procedure.
The stored procedure looks like this.
CREATE PROCEDURE spOrderPlaatsen
(
#tijd time(0),
#klantnr integer,
#ophaaldatum date,
#afleverdatum date,
#palletnr integer,
#aantal integer,
#Adres Varchar(255)
)
AS
BEGIN TRANSACTION
DECLARE #ordernr int
DECLARE #besteldatum date
set #besteldatum = getdate()
SELECT #ordernr = MAX(o.ordernr) + 1
FROM orders o
insert into orders values (#ordernr, #besteldatum, #tijd, #klantnr, #ophaaldatum, #afleverdatum, #adres)
insert into orderregel values (#ordernr, #palletnr, #aantal)
IF ##ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error tijdens het plaatsen van order.', 16, 1)
RETURN
END
COMMIT
go
Somehow we get a conversion error that we cannot find.
Could any1 figure this out for us? It would be greatly appreciated
There are multiple places where this could be going wrong. Here is some advice:
Execute the stored procedure with explicit parameters (see here for an example). Do not ever just dump the parameters into the query string.
Always list the columns for an insert. So, this should be insert into orders(col1, col2, col3, . . .) for whatever columns you are including.
Use identity so ordernr is calculated automatically by the database. You can get the value using an OUTPUT clause in the INSERT.
Similarly, you might want besteldatum to default to the current date -- or not. I'm not sure what this column really is, but a default would be appropriate for a create date column.
Surround the entire body of the stored procedure in its own BEGIN/END block (don't depend on the BEGIN TRANSACTION.
I'm using SQL Server as my DBMS and I have 2 tables namely Person and Voter.
Person has these columns:
PersonId (int, primary key auto-increment int_identity),
FirstName (nvarchar(50))
LastName (nvarchar(50))
Voter has these columns:
VoterPersonId (int, foreign key)
VoterPlace (nvarchar(50))
These 2 tables are related. For 1 person there can only be 1 voter place. So you may call it a one is to one relationship. I created 2 tables because there are also people who aren't voters that I must include in my database and I don't want to create null values so I made a separate table which is the 'voter' table. Basically, I wanted to know the number registered voters and non-voters in our city. Now, I have created a 'save' button in VB.NET and used the following code to insert information into my tables:
Dim sql As New SQLControl
Private Sub cmdSave_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
sql.con.Open()
Using cmdPerson As New SqlClient.SqlCommand("INSERT INTO Person(FirstName, LastName) VALUES('" & txtFirstName.Text & "', '" & txtLastName.Text & "')", sql.con)
cmdPerson.ExecuteNonQuery()
End Using
Using cmdVoter As New SqlClient.SqlCommand("INSERT INTO Voter(VoterPlace) VALUES('" & txtVoterPlace.Text & "')", sql.con)
cmdVoter.ExecuteNonQuery()
End Using
sql.con.Close()
End Sub
Now, my problem is I don't know how to transfer the value of 'PersonId' primary key which is auto-increment in_identity into 'VoterPersonId' the moment I click on the 'save' button. Is it possible? Can you please help me on this matter? I would really appreciate it.
You can execute both queries in a single stored procedure
CREATE PROCEDURE InsertPerson
#firstname varchar(50),
#lastname varchar(50),
#voterPlace varchar(50)
AS
declare #newid int
INSERT INTO Person(Firstname, Lastname) VALUES (#firstname, #lastname)
SELECT #newid = SCOPE_IDENTITY()
INSERT INTO Voter(VoterPersonId, VoterPlace) VALUES ( #newid, #voterPlace)
You can use a stored procedure but you certainly don't have to. The principle is still the same though. You execute the insert to the parent table and then use the SCOPE_IDENTITY function to get the auto-generated ID. You would then use an output parameter to get that value back into your app so that you can include it in the next insert to the child table, e.g.
Using connection As New SqlConnection("connection string here"),
parentCommand As New SqlCommand("INSERT INTO Parent (ParentName) VALUES (#ParentName); SET #ParentId = SCOPE_IDENTITY();", connection),
childCommand As New SqlCommand("INSERT INTO Child (ParentId, ChildName) VALUES (#ParentId, #ChildName)", connection)
With parentCommand.Parameters
.AddWithValue("#ParentName", parentName)
.Add("#ParentId", SqlDbType.Int).Direction = ParameterDirection.Output
End With
connection.Open()
Dim transaction = connection.BeginTransaction()
Try
parentCommand.ExecuteNonQuery()
With childCommand.Parameters
.AddWithValue("#ParentId", parentCommand.Parameters("#ParentId").Value)
.AddWithValue("#ChildName", childName)
End With
childCommand.ExecuteNonQuery()
transaction.Commit()
Catch
transaction.Rollback()
End Try
End Using
I'm using MS Access 2010 and I'm trying to create tables using SQL. I would like to put in some check constraints but I'm having some troubles:
CREATE TABLE Test (
tester Text CHECK (tester IN ('ABC', 'BCD', 'CDE'))
);
I'm getting a syntax error,
Any suggestions?
Thank you!
EDIT: Sorry if I wasn't clear. What I would like actually is to CHECK that tester is either "ABC", "BCD" or "CDE" those are the only values he can have.
EDIT2: I tried something else:
CREATE TABLE Test (
tester Text NOT NULL,
CONSTRAINT m_pk PRIMARY KEY(tester),
CONSTRAINT check_tester CHECK (DATALENGTH(tester) > 2)
);
and I also get a syntax error. Is there something I'm really not understanding with checking Text values? I can't possibly see where either of these is wrong.
Beginning with Jet 4, CHECK contraints are supported for Access DDL executed from ADO, but not from DAO.
You can execute a single DDL statement which creates the table Test with your constraint. You don't need to execute one statement to create the table and then another to add the constraint.
CREATE TABLE Test
(
tester TEXT(255),
CONSTRAINT ABC_or_BCD_or_CDE CHECK
(
tester IN ('ABC', 'BCD', 'CDE')
)
);
I formatted it that way to make it easier to examine the pieces. You could use this VBA to execute the statement:
strSql = "CREATE TABLE Test ( tester Text(255)," & vbCrLf & _
"CONSTRAINT ABC_or_BCD_or_CDE" & vbCrLf & _
"CHECK ( tester IN ('ABC', 'BCD', 'CDE')));"
Debug.Print strSql
CurrentProject.Connection.Execute strSql
Notes:
CurrentProject.Connection is an ADO object, so its .Execute method succeeds. The same statement with CurrentDb.Execute (a DAO method) would fail.
With ADO, declaring a field as TEXT without including a length (tester TEXT instead of tester TEXT(255)) will give you a memo field.
You will need to run against a connection:
ssql = "CREATE TABLE Test (tester Text)"
CurrentProject.Connection.Execute ssql
ssql = "ALTER TABLE test ADD CONSTRAINT " _
& "myrule CHECK (tester IN ('ABC', 'BCD', 'CDE'))"
CurrentProject.Connection.Execute ssql
Or
sSQL = "CREATE TABLE Test (tester Text, " _
& "CONSTRAINT myrule CHECK (tester IN ('ABC', 'BCD', 'CDE')))"
Note that the name, myrule in this case, must not already exists, even for a different table.
Some notes: Is it possible to create a check constraint in access and/or DAO?
My bad,
It appears MS Access does not allow CHECK Constraints except for primary and foreign keys. My teacher taught her course with Oracle until last year and apparently did not see that this could not be done in MS Access.
I am trying to create a check constraint on an access (jet?) table.
So, I open the .mdb file with access, go into queries->create query in design view,
type esc, then menu->view->query and finally type
create table X (
a number,
check (a > 20)
)
but access thinks that I have a "syntax error in field definition". However, I don't think so. Therefore my question: is it possible to create a check constraint with access. If so: how.
Additionally, I'd like to create the constraint with dao/vba, not on the GUI. Is that possible?
And lastly, on a slightly related note: how do you enter sql statements into access. I can't imagine that I have to use the queries->design view->query->view route in order to do that. I am used to Oracle's SQL*Plus, which I like very much, and I'd hope there's something similar for access as well.
Thanks for any input
Rene
Here are some notes.
You can create a Pass-Through query for Oracle (Select menu "Query" > "SQL Specific" > "Pass-Through")
Since Access 2003, you can select SQL Server Compatible Syntax (ANSI 92) (http://office.microsoft.com/en-us/access/HA010345621033.aspx)
A validation rule with VBA / DAO
''Reference: Microsoft DAO x.x Object Library
Dim tdf As TableDef
Dim db As Database
Set db = CurrentDb
Set tdf = db.TableDefs("Table1")
tdf.Fields("aDouble").ValidationRule = "<10"
tdf.Fields("aDouble").ValidationText = "Must be less than 10"
Constraints with ADO / VBA. See [Intermediate Microsoft Jet SQL for Access 2000](http://msdn.microsoft.com/en-us/library/aa140015(office.10).aspx)
''Reference: Microsoft ADO Ext. x.x for DDL and Security
Dim cn As ADODB.Connection 'For action queries
Dim rs As ADODB.Recordset 'For select queries
Dim s As String
Dim RecordsAffected As Long
Set cn = CurrentProject.Connection
''You can store sql in a table
s = DLookup("SQLText", "sysSQL", "ObjectName='q1'")
''Result: CREATE TABLE tblCreditLimit (LIMIT DOUBLE)
cn.Execute s, RecordsAffected
Debug.Print RecordsAffected
''You can run queries from VBA
s = "INSERT INTO tblCreditLimit VALUES (100)"
cn.Execute s, RecordsAffected
Debug.Print RecordsAffected
s = "CREATE TABLE tblCustomers (CustomerID COUNTER, CustomerName Text(50))"
cn.Execute s, RecordsAffected
Debug.Print RecordsAffected
s = "INSERT INTO tblCustomers VALUES (1, 'ABC Co')"
cn.Execute s, RecordsAffected
Debug.Print RecordsAffected
s = "ALTER TABLE tblCustomers " _
& "ADD COLUMN CustomerLimit DOUBLE"
cn.Execute s, RecordsAffected
Debug.Print RecordsAffected
''You can add contraints using ADO like so:
s = "ALTER TABLE tblCustomers " _
& "ADD CONSTRAINT LimitRule " _
& "CHECK (CustomerLimit <= (SELECT LIMIT " _
& "FROM tblCreditLimit))"
cn.Execute s, RecordsAffected
Debug.Print RecordsAffected
s = "UPDATE tblCustomers " _
& "SET CustomerLimit = 200 " _
& "WHERE CustomerID = 1"
''Error occurs here
cn.Execute s, RecordsAffected
s = "UPDATE tblCustomers " _
& "SET CustomerLimit = 90 " _
& "WHERE CustomerID = 1"
cn.Execute s, RecordsAffected
Debug.Print RecordsAffected
''Clean up
''You cannot do this through the database window,
''because of the constraint.
s = "ALTER TABLE tblCustomers DROP CONSTRAINT LimitRule "
cn.Execute s, RecordsAffected
Debug.Print RecordsAffected
s = "DROP TABLE tblCustomers "
cn.Execute s, RecordsAffected
Debug.Print RecordsAffected
s = "DROP TABLE tblCreditLimit "
cn.Execute s, RecordsAffected
Debug.Print RecordsAffected
There is Validation rule on a column.
You can use VB for Access. no SQL*Plus here...
You can always use SQL Express as a data source - with all the benefits of real sql server and use access only as a front.
To do this in Access, you need to first open the interface into ANSI-92 Query Mode. I've tested your SQL DDL code: it works fine and creates a column of type FLOAT (Double).
Is is not possible to do this using DAO but you can use ADO. Long story short: CHECK constraints were introduced into the engine in the Jet 4.0 era when the Access Team were favouring ADO. With effect from Access2007, the Access Team are back to favouring DAO but have yet to plug the Jet 4.0 'holes' in DAO. So for the majority of Jet 4.0 -only functionality (compressible data types, fixed-length text data types, fast foreign keys, etc) you need to use ADO.
You can’t use standard ANSI in the query builder UNLESS you set the database as sql ansi compatible. If you do change this setting, then you CAN can use the sql in the query builder as you have. I would not recommend changing this setting for existing databases however.
If you do, you could type in:
CREATE TABLE z1
(id int IDENTITY , FirstName CHAR, LastName CHAR, SSN INTEGER ,
check (id < 20),
constraint Mypk primary key (id) )
In you don’t need to save the sql in the query builder, and just want to type in the sql, then simply whack ctrl-g to get the access command line prompt, and you can then type in:
currentproject.Connection.Execute "CREATE TABLE
z1(id int IDENTITY , FirstName CHAR, LastName CHAR, SSN INTEGER ,
check (id < 20),
constraint Mypk primary key (id) )"
The above would be typed on one line. So, you can use the command line prompt if you want..