Table valued function parameter as varchar - sql

I have this table-valued function in my SQL Server 2008 database:
Create FUNCTION dbo.fct1(#Code varchar(10) )
RETURNS TABLE
AS
RETURN
(
select CODE , NOM
from CODIF
where NUMERO = 'TP'
and CODE = #Code
)
When I call it from my code :
sSQL = "select * from fct1(" & Code & ")"
Dim cmd As New SqlCommand(sSQL, Connection)
If Connection.State <> ConnectionState.Open Then Connection.Open()
Dim rd As SqlClient.SqlDataReader
rd = cmd.ExecuteReader()
I get this error :
column name not valid : 'EA2'
I need to know :
What is the reason of this error?
How can I fix it?

You're missing the ' from the sql.
You should probably parameterise the SQL and try to use using as well:
using conn as new sqlconnection(connstring), comm as new sqlcommand("",conn)
conn.open()
comm.commandtype = commandtype.text
comm.commandtext = "select * from fct1(#Code)"
comm.parameters.addwithvalue("#Code",Code)
Dim rd as sqldatareader = comm.executedatareader
end using

Missed '
sSQL = "select * from fct1('" & Code & "')"
Dim cmd As New SqlCommand(sSQL, Connection)
If Connection.State <> ConnectionState.Open Then Connection.Open()
Dim rd As SqlClient.SqlDataReader
rd = cmd.ExecuteReader()

Related

Vb.Net 2010 - SQL Insert Command with autonumeric value

I'm looking to add a row with an autonumeric value using SQL.
I'm using Studio VB 2010. I have a very simple table with 2 fields:
ID Autonumeric
Model Text field.
constr = "INSERT INTO procedures VALUES('" & txtFName.Text & "')"
cmd = New OleDbCommand(constr, cn)
cn.Open()
Me.i = cmd.ExecuteNonQuery
A message says a parameter is missing,
so my question is...
How can I add in the SQL command this automatic value? (ID)
Should I get the last ID number and +1 ?? I think there's gotta be a simple way to do it.
Thank you.
Update #1
I am now trying parameterized queries as suggested...
I found this example,
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.Add("#a1", OleDbType.Integer).Value = 0
.Add("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
But still, I'm geting a Syntaxis error.
Any thoughts?
Thanks to you all.
UPDATE #2
This code seems to work if I give the next ID number, but again, how can I do it automatically?
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#a1", OleDbType.Integer).Value = 3
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
Any comments? Thanks again.
UPDATE #3 This Code gives me Syntaxis Error
I just put my only one column to update, the second one is the autonumber column, as I was told to try.
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO procedures (procedure) VALUES ('Model')"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
Try
Con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try
UPDATE #4 - SOLUTION
I'm putting this code in here in case someone finds it useful.
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;"
dbSource = "Data Source = c:\gastrica\dabase.accdb"
Con.ConnectionString = dbProvider & dbSource
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO [procedures] ([procedure]) VALUES (?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#procedure", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
Dim varProcedure As String = cmd.Parameters("#procedure").Value.ToString()
MessageBox.Show("Record inserted successfully. Procedure = " & varProcedure)
Catch ex As Exception
Throw ex
Finally
Con.Close()
End Try
Thanks all for your comments and help.
You need to specify the columns:
INSERT INTO procedures (columnname, columnname2) VALUES ('test', 'test');
Here is a sql fiddle showing an example:
http://sqlfiddle.com/#!9/3cf706/1
Try this one:
constr = "INSERT INTO procedures (ID, Model) VALUES (0,'" & txtFName.Text & "')"
'or (not sure)
constr = "INSERT INTO procedures (Model) VALUES ('" & txtFName.Text & "')"
When use 0 as value, in autonumeric fields SQL insert the next number
Thanks for your answers.
I couldnĀ“t do it, it gives me errors. So I end up with a single variable reaching the next Auto Value. Using a simple SQL command.
And then, everything runs good.
vNextAuto = GetDB_IntValue("SELECT TOP 1 * FROM procedures ORDER BY ID DESC", "ID") + 1
Dim SQL_command As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#id", OleDbType.Integer).Value = vNextAuto
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
'Dim id As String = cmd.Parameters("#id").Value.ToString()
'MessageBox.Show("Record inserted successfully. ID = " & id)
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try

Getting Primary key values (auto number ) VB

I have a database on Access and I want to insert into 2 tables
ReportReq
req_sysino
I want to get the last value of primary key (auto numbered) and insert it into req_sysino
, I am stuck with this code and I dont know how to proccess
Private Function InsertSysInvToDB(intSysInv As Integer) As Integer
Dim strSQLStatement As String = String.Empty
Dim intNoAffectedRows As Integer = 0
Dim con As New OleDb.OleDbConnection("PROVIDER = Microsoft.ace.OLEDB.12.0; Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb")
Dim cmd As OleDb.OleDbCommand
Dim reqnum As String = "Select ##REQ_NUM from ReportReq"
strSQLStatement = "INSERT INTO req_sysino (Req_num, sysinvo_ID)" +
" VALUES (" & reqnum & "','" & intSysInv & ")"
cmd = New OleDb.OleDbCommand(strSQLStatement, con)
cmd.Connection.Open()
intNoAffectedRows = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Return intNoAffectedRows
End Function
this is my insert code that should generate autonumber
Dim dbProvider = "PROVIDER = Microsoft.ace.OLEDB.12.0;"
Dim dbSource = " Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb"
Dim sql = "INSERT INTO ReportReq (Emp_EmpID, Req_Date,Req_expecDate,Req_repnum, Req_name, Req_Descrip, Req_columns, Req_Filtes, Req_Prompts)" +
"VALUES (#reqNUM,#reqName,#reqDescrip,#reqcolumns,#reqfilters,#reqprompts)"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("#EmpID", txtEmpID.Text)
cmd.Parameters.AddWithValue("#reqDate", DateTime.Today)
cmd.Parameters.AddWithValue("#reqExpecDate", DateTime.Parse(txtbxExpecDate.Text).ToShortDateString())
cmd.Parameters.AddWithValue("#reqNUM", txtRep_NUM.Text)
cmd.Parameters.AddWithValue("#reqName", txtRep_Name.Text)
cmd.Parameters.AddWithValue("#reqDescrip", txtbxRep_Desc.Text)
cmd.Parameters.AddWithValue("#reqcolumns", txtbxColReq.Text)
cmd.Parameters.AddWithValue("#reqfilters", txtbxFilReq.Text)
cmd.Parameters.AddWithValue("#reqprompts", txtbxPromReq.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Immediately after you ExecuteNonQuery() your INSERT INTO ReportReq ... statement you need to run a
SELECT ##IDENTITY
query and retrieve its result, like this
cmd.ExecuteNonQuery() ' your existing statement to run INSERT INTO ReportReq
cmd.CommandText = "SELECT ##IDENTITY"
Dim newAutoNumberValue As Integer = cmd.ExecuteScalar()

How to catch oledbdatareader errors

I have this code i wrote to find out if a record exists in data base. It works well when record is found. If it isn't, it brings up an error. I would like the error to be caught in a messagebox that states "record not found" instead.
Dim findprinc As String = TextBox1.Text.Substring(0, 16)
MsgBox(findprinc)
sql = "Select RealID from Dets where ID like '%" & findprinc & "%'"
MsgBox(sql)
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\new.mdb")
conn.Open()
Dim cmd As New OleDbCommand(sql, conn)
Dim numeri As OleDbDataReader = cmd.ExecuteReader
numeri.Read()
Dim findprinc As String = TextBox1.Text.Substring(0, 16)
MsgBox(findprinc)
Sql = "Select RealID from Dets where ID like '%" & findprinc & "%'"
MsgBox(Sql)
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Persist Security Info=false; Data Source=..\new.mdb")
conn.Open()
Dim cmd As New OleDbCommand(Sql, conn)
Dim numeri As OleDbDataReader = cmd.ExecuteReader
Dim recordFound As Boolean = False
While numeri.Read
recordFound = True
End While
If recordFound = False Then
MsgBox("Record Not Found")
End If

syntax error on create table

When I use this code to create a table in my access db, I get an error message saying that there is a syntax error in my create sentence
What am I doing wrong.
Dim min_path As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
Dim min_path_trimmed As String = Replace(min_path, "file:\", "")
Dim SQL As String
Dim objCmd As New OleDbCommand
Dim Con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + min_path_trimmed + "\db.mdb")
SQL = "CREATE TABLE Names (LastName VARCHAR(30), FirstName VARCHAR (30))"
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
objCmd.ExecuteNonQuery()
Con.Close()
MsgBox("Table has been created")
Try to change your Query from
SQL = "CREATE TABLE Names (LastName VARCHAR(30), FirstName VARCHAR (30))"
to
SQL = "CREATE TABLE Names (LastName Text(30), FirstName Text(30))"
Hi this is the way to create table in the database
Dim databaseName As String = "D:\NewDB.mdb"
Dim tableName As String = "Employee"
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\NewDB.mdb")
con.Open()
Dim dbSchema As DataTable = con.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, tableName, "TABLE"})
con.Close()
Dim cmd As New OleDb.OleDbCommand("CREATE TABLE [" + tableName + "] ([EmpName] TEXT(10), [EmpAddress] TEXT(10))", con)
con.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Table Created Successfully")
con.Close()
If you get any errors please feel free to post back
I will be glad to help.
Regards.

How to get last auto increment value in a table? VB.NET

How would you get the last Primary Key/Auto Increment value in a table using OleDb?
I need to get this value so I can create a folder for a record before it is added so that files can be copied to the folder when it is added.
Any idea?
I have tried as following.
##Identity 'Need to insert a record first and I can't do that without copying the files first
SELECT SCOPE_IDENTITY() 'Doesn't work with OleDb
This is the error message I get:
I think this might work:
SELECT MAX(ID) FROM MyTable
you can do it like this because of The Jet 4.0 provider supports ##Identity,
Reference
Dim query As String = "Insert Into Categories (CategoryName) Values (?)"
Dim query2 As String = "Select ##Identity"
Dim ID As Integer
Dim connect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", Category.Text)
conn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = query2
ID = cmd.ExecuteScalar()
End Using
End Using
Try this
Select IDENT_CURRENT('TableName')
It Will retrun Last ID(If it's Auto increment) of your Table
reference
**c#**
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
**VB**
Dim query As String = "Insert Into Categories (CategoryName) Values (?)"
Dim query2 As String = "Select ##Identity"
Dim ID As Integer
Dim connect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", Category.Text)
conn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = query2
ID = cmd.ExecuteScalar()
End Using
End Using
refer
You can try Check if NULL first :
Select if(IsNull(Max(ColName)),1,Max(ColName) + 1 ) From YourTable
try this (vb.net)
'''
Dim lastrecord As Integer
Dim command As New SqlCommand("Select IDENT_CURRENT('tbluom')+1", conn)
command.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New SqlDataAdapter(command)
lastrecord = command.ExecuteScalar()
txt_uomid.Text = lastrecord
MsgBox(lastrecord)
Dim encode As String = txt_uomid.Text '"99999"
Dim encint As Integer = Integer.Parse(encode) '+ 1
encode = "00" & "-" & encint.ToString("00000").Substring(1, 4)
MsgBox(encode)
''''