Cannot find the Nvarchar to Int conversion in my code - sql

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.

Related

SQL syntax error in updating a database value

I'm update the money for one person only in a database. The money is saved as a currency and the email as a string. My SQL is throwing a syntax error
ADOQuery.sql.text:= ' UPDATE TblPlayerdetails SET Money = "' + Inttostr(NewAmount) + '" WHERE Email = "' + Playersemail + '"';
Newamount is an integer and email is a string.
I was hoping you would manage to work out what to do from the documentation I linked in comments, but on reflection I thought I had better provide a correct answer.
Set up the following code
procedure TForm1.Button1Click(Sender: TObject);
begin
AdoQuery2.SQL.Text := 'update moneytable set money = :money where id = :id';
AdoQuery2.Parameters.ParamByName('ID').Value := 1;
AdoQuery2.Parameters.ParamByName('Money').Value := 99;
AdoQuery2.ExecSQL;
end;
The line
AdoQuery2.SQL.Text := 'update moneytable set money = :money where id = :id';
sets up a parameterised UPDATE statement. The :id and :money are placeholders for parameter values which will be provided separately. The parameter names are ID and Money, though they could be given other names. Note that you could set up AdoQuery2's SQL.Text in the IDE at design time if you wanted to.
The next two lines
AdoQuery2.Parameters.ParamByName('ID').Value := 1;
AdoQuery2.Parameters.ParamByName('Money').Value := 99;
specify the values which the parameters are to be set to for when the UPDATE is actually executed. The ID value is the Row iD (aka primary key) of the row in the table which is to be updated. Before the UPDATE staement is actually executed, the AdoQuery parses the SQL and creates the parameters if they don't alteady exist (you can create them at design time in the IDE by editing the Parameters property of the AdoQuery.
Finally
AdoQuery2.ExecSQL;
is what actually executes the UPDATE statement. Note that you can repeat the steps of setting the parameter values and calling ExecSQL as many times as you want.
The main thing which was wrong with your UPDATE statement was that you were using double-quote (") marks, whereas when a SQL statement needs quote marks (and values of numeric columns do NOT) they should be single quotes('). A complication when constructing a SQL statement in Delphi code is that its syntax requires single quotes which are to be embedded in the SQL to be doubled up.
Note also that you should always used parameterised SQL for your SELECT, UPDATE, INSERT and DELETE statements as this helps protect your app against Sql injection. Making, say, an unparameterised statement accessible to the user can allow a malicious user to attempt to execute any SQL they wish.
In your question, you did not indicate what type of column is 'Money'. If it's varchar, char, then I understand why you might convert NewAmount to a string.
However, if the database expects numeric value (because the field is of type int, double, dec, or float), the syntax would be SET Money= '+ NewAmount +'.

Sending to SQL several sequential Queries using Power Query

dear brothers-in-codes =)
By now i'm using Power Query for quite a long time to communicate with SQL Server.
I already now how to sent data from Excel Table to SQL Table using INSERT... , UPDATE... , DELETE... instructions.
Yet currently i faced a problem, when i was trying to
Create table
Populate it with the data from Excel Table.
I understood that just have no idea, how to send 2 sequential Queries with
CREATE SCHEMA... & CREATE TABLE... instructions
with INSERT INTO... instruction, passing to this Query Table Columns as parameters
Currently my PQ Function looks like this (the commented part is something that I do manually in SSMS before launching the PQ Function from Excel):
(mCourses, mSQLCourseCode, mOwnToolkit, mTuition, mToolkit, mTuitionDeposit, mInstalments, mAcadDuration, mType, mDateOfUpload)=>
let
Source = Sql.Database("<a.d.re.ss>", "<DB.Name>",
[Query="
use EnvirotechFinance
--GO
--if schema_id('price') is null
--execute('CREATE SCHEMA price');
--GO
--drop table if exists price.Price
--Create table price.Price
--(
-- Courses nvarchar(255),
-- SQLCourseCode nvarchar(255),
-- OwnToolkit int,
-- Tuition decimal(12,5),
-- Toolkit decimal(12,5),
-- TuitionDeposit decimal(12,5),
-- Instalments int,
-- AcadDuration int,
-- Type int,
-- DateOfUpload date
--)
insert into price.Price
( Courses,
SQLCourseCode,
OwnToolkit,
Tuition,
Toolkit,
TuitionDeposit,
Instalments,
AcadDuration,
Type,
DateOfUpload
)
Values ('" & mCourses &"', '"& mSQLCourseCode &"', '"& mOwnToolkit &"', '"& mTuition &"', '"& mToolkit &"',
'"& mTuitionDeposit &"','"& mInstalments &"', '"& mAcadDuration &"', '" & mType & "', '" & mDateOfUpload & "')
"])
in
Source
You could make another step which depends on the Source step that also calls Sql.Database with the second query.
However, using Power Query in this fashion is highly discouraged. Native queries should be used for complex read queries or stored procedures, but they should not be used for modifying the database itself. In other words, running INSERT or DELETE operations in Power Query should be avoided. This is because Power Query may re-evaluate the query multiple times, so you can end up inserting a row several more times than you expected.

vb.net foreign key insert sql statement

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.

How to increment ID by 1 in SQL Server (backend) when INSERT code is written in vba (frontend)?

I am new to this forum.
I have the following environment: an Access frontend client that is connected to a database on SQL Server (backend). I would like to use an Access form to enter data that is associated with a specific ID number (in database Table). Ideally the ID will automatically increment when an INSERT is made to the Table. The vba code (based on the SQL query) I wrote is the following:
Option Compare Database
Option Explicit
Private Sub List0_Click()
Dim HelloWORLD As String
Dim dbsCurrent As Database
Set dbsCurrent = CurrentDb
CurrentDb.Execute "INSERT INTO Table1 (TESTING_1, TESTING_2) VALUES (" & 9 & "," & HelloWORLD & ")"
End Sub
The code is compiling but it is not appending the Table1 like it is supposed to do. Please Help.
You can use sequences.
You can creates sequence MySequence1 and use it:
CurrentDb.Execute "INSERT INTO Table1 (TESTING_1, TESTING_2) VALUES (NEXT VALUE FOR MyDemoSequence," & HelloWORLD & ")"
Can you make the ID field an IDENTITY field within SQL Server? This will automatically increment whenever a new row is inserted. Example from Microsoft documentation:
CREATE TABLE new_employees
(
id_num int IDENTITY(1,1),
fname varchar (20),
minit char(1),
lname varchar(30)
)
The first number is the seed, and the second is the increment, so IDENTITY(1,1) means start at '1', and increase by '1' each time.
You can retrieve the ID that was created using SELECT SCOPE_IDENTITY(); following the insert if necessary.

INSERT INTO SELECT - large amount of records

I want to insert records into a TempTable. Something like this:
insert into ##tempT
SELECT * FROM MyTable
MyTable contains a large amount of records so the "insert into" takes a long time.
If I try to run:
SELECT COUNT(*) FROM ##tempT
it returns always "0" until all records from "MyTable" are inserted by INSERT INTO command.
How can I get a progress count that advise me how many records are in ##tempT?
I need to update a progress bar value while the SQL command is running.
Thank you.
try
set transaction isolation level read uncommitted
SELECT COUNT(*) FROM ##tempT
You can split your query up.
x = number of records in MyTable / 100
i = 0
do until we're done
queryString = "insert into ##tempT "
queryString += "select top " + x " + " * FROM MyTable "
queryString += "where RecordNumber > " + i
Execute queryString
Update Progress Bar
i = i + x
loop
You'll notice that you'll need some sort of RecordNumber field to make this work though. There are various ways to accomplish that you can search for.
Use a stored procedure and DECLARE a variable COUNT and treat this as a looping variable and each time an insert is done, increment COUNT by 1 and keep printing it using another query whenever you want to know the count .Or, return this count from the procedure and read it into your program for updating the progress bar. :)