Executing a stored procedure in vb - sql

I'm using the current code to try to execute a stored procedure, and it shows no errors, but the update made by the procedure is not executed.
Public Function UpdateRouteByRegister(ByVal conexion As String, ByVal idRegister As Integer, ByVal route As String) As Boolean
Try
ConnectionString = conexion
myConnection = New SqlConnection(ConnectionString)
myDataAdapter = New SqlDataAdapter("spUpdateHistoricLoad", myConnection)
myDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
myDataAdapter.SelectCommand.Parameters.Add(New SqlParameter("#idRegister", SqlDbType.Int))
myDataAdapter.SelectCommand.Parameters("#idRegister").Value = idRegister
myDataAdapter.SelectCommand.Parameters.Add(New SqlParameter("#route", SqlDbType.VarChar, 100))
myDataAdapter.SelectCommand.Parameters("#route").Value = route
myDataAdapter.SelectCommand.CommandTimeout = 0
myDataset = New DataSet
myDataAdapter.Fill(myDataset)
myDataset.Dispose()
myConnection.Close()
Log("******* Register updated = " + idRegister.ToString + " *******")
Return True
Catch objException As Exception
Log("******* Error on updating register = " + idRegister.ToString + " *******")
Return False
End Try
End Function
The SQL Stored Procedure is the following:
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spUpdateHistoricLoad]
#idRegister INTEGER,
#route VARCHAR(100)
AS
BEGIN
UPDATE tOperation SET ImagenMulti = #route WHERE IDRegister = #idRegister
END

I would suggest dropping the DataAdapter and DataSet objects and just use a SqlCommand:
Public Function UpdateRouteByRegister(ByVal conexion As String, ByVal idRegister As Integer, ByVal route As String) As Boolean
Try
ConnectionString = conexion
myConnection = New SqlConnection(ConnectionString)
myConnection.Open
Dim cmd as SqlCommand
cmd = New SqlCommand("spUpdateHistoricLoad", myConnection)
cmd.Parameters.AddWithValue("#idRegister", idRegister)
cmd.Parameters.AddWithValue("#route", route)
cmd.CommandTimeout = 0
cmd.ExecuteNonQuery
myConnection.Close()
Log("******* Register updated = " + idRegister.ToString + " *******")
Return True
Catch objException As Exception
Log("******* Error on updating register = " + idRegister.ToString + " *******")
Return False
End Try
End Function

Related

Converting Access OLE object image to show in Datagridview vb.net

I'm trying to load data from an Access database into a DataGridView.
This is my access database - Image has long binary data
However, when I retrieve the data from the database and try to load it into the DataGridView, it shows this error:
I have 2 forms, this one is for adding to database:
This one is for showing the database in the DataGridView
Here's my code to add my uploaded image to database.
Dim fsreader As New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read)
Dim breader As New BinaryReader(fsreader)
Dim imgbuffer(fsreader.Length) As Byte
breader.Read(imgbuffer, 0, fsreader.Length)
fsreader.Close()
Dim create As New OleDbCommand("INSERT INTO Officials ([officialname] , [age] , [birthdate] , [position] , [term], [status], [image] ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "' , '" & DateTimePicker1.Value & "' , '" & cb1 & "' , '" & TextBox3.Text & "' , '" & status & "' , #img )", con)
With create
.Parameters.Add("#on", OleDb.OleDbType.VarChar).Value = TextBox1.Text.Trim
.Parameters.Add("#age", OleDb.OleDbType.VarChar).Value = TextBox2.Text.Trim
.Parameters.Add("#bd", OleDb.OleDbType.VarChar).Value = DateTimePicker1.Value
.Parameters.Add("#pn", OleDb.OleDbType.VarChar).Value = cb1
.Parameters.Add("#tm", OleDb.OleDbType.VarChar).Value = TextBox3.Text.Trim
.Parameters.Add("#st", OleDb.OleDbType.VarChar).Value = status
.Parameters.Add("#img", OleDb.OleDbType.LongVarBinary).Value = imgbuffer
I can give you an example how to put images on a DataGridView from Access but you'll need to adapt to your reality.
Just add a DataGridView and create 2 columns, first as TextBoxColumn and second as ImageColumn.
The next step is to load data from access database, so use what you already have that is not shown in your post. It will be something like:
Dim GConn As New OleDbConnection("your connection string...")
Dim GCmd As New OleDbCommand()
Dim DtReader As OleDbDataReader
GCmd.Connection = GConn
GCmd.CommandText = "SELECT PhotoDescription, PhotoOLE FROM MY_TABLE;"
DtReader = GCmd.ExecuteReader ' DtReader will have all the rows from database
' For this test you need to load less than 100 records
dim iLine as integer=0
DataGridView1.rows.Add(100) ' add 100 rows to test
DtReader.Read ' read first record
Do
DataGridView1.Rows(iLine).Cells(0).Value=DtReader("PhotoDescription").ToString
DataGridView1.Rows(iLine).Cells(1).Value=CType(DtReader("PhotoOLE"), Byte())
iLine+=1
Loop while DtReader.Read
It's not necessary to store both birthdate and age, because one of them can be computed given a value for the other one.
You haven't provided enough code to identify the issue, but if the image data wasn't properly converted before storing it, that would cause an issue.
Below shows how to both insert and update data that contains an image, as well as how to retrieve the data. In the code below, you'll also find code that will create an Access database and a table.
Add a reference to Microsoft ADO Ext. 6.0 for DDL and Security
Note: This is required for the "CreateDatabase" function in the code below.
In VS menu, click Project
Select Add Reference...
Select COM
Check Microsoft ADO Ext. 6.0 for DDL and Security
The code is tested and fairly well-documented. Of particular importance are the following functions/methods:
GetImageAsByteArray
TblOfficialsExecuteNonQuery
TblOfficialsInsert
TblOfficialsGetData
Create a class (name: HelperAccess.vb)
Imports System.Data.OleDb
Imports System.IO
Public Class HelperAccess
Private _accessFilename As String = String.Empty
Private _connectionStr As String = String.Empty
Public ReadOnly Property AccessFilename
Get
Return _accessFilename
End Get
End Property
Sub New(accessFilename As String, Optional dbPassword As String = "")
'set value
_accessFilename = accessFilename
'create connection string
If Not String.IsNullOrEmpty(dbPassword) Then
_connectionStr = String.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0};Jet OLEDB:Database Password='{1}'", accessFilename, dbPassword)
Else
_connectionStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};", _accessFilename)
End If
End Sub
Public Function CreateDatabase() As String
Dim result As String = String.Empty
Dim cat As ADOX.Catalog = Nothing
Try
'create New instance
cat = New ADOX.Catalog()
'create Access database
cat.Create(_connectionStr)
'set value
result = String.Format("Status: Database created: '{0}'", _accessFilename)
Return result
Catch ex As Exception
'set value
result = String.Format("Error (CreateDatabase): {0}(Database: {1})", ex.Message, _accessFilename)
Return result
Finally
If cat IsNot Nothing Then
'close connection
cat.ActiveConnection.Close()
'release COM object
System.Runtime.InteropServices.Marshal.ReleaseComObject(cat)
cat = Nothing
End If
End Try
End Function
Public Function CreateTblOfficials() As String
Dim result As String = String.Empty
Dim tableName As String = "Officials"
Dim sqlText = String.Empty
sqlText = "CREATE TABLE Officials "
sqlText += "(ID AUTOINCREMENT not null primary key,"
sqlText += " [FullName] varchar(50) not null,"
sqlText += " [Birthdate] DateTime,"
sqlText += " [JobDescription] varchar(50) not null,"
sqlText += " [Term] varchar(50),"
sqlText += " [Status] varchar(50) not null,"
sqlText += " [Photo] Longbinary);"
Try
'create database table
ExecuteNonQuery(sqlText)
result = String.Format("Table created: '{0}'", tableName)
Catch ex As OleDbException
result = String.Format("Error (CreateTblOfficials - OleDbException): Table creation failed: '{0}'; {1}", tableName, ex.Message)
Catch ex As Exception
result = String.Format("Error (CreateTblOfficials): Table creation failed: '{0}'; {1}", tableName, ex.Message)
End Try
Return result
End Function
Private Function ExecuteNonQuery(sqlText As String) As Integer
Dim rowsAffected As Integer = 0
'used for insert/update
'create new connection
Using cn As OleDbConnection = New OleDbConnection(_connectionStr)
'open
cn.Open()
'create new instance
Using cmd As OleDbCommand = New OleDbCommand(sqlText, cn)
'execute
rowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
Return rowsAffected
End Function
Public Function GetImageAsByteArray(filename As String) As Byte()
'read image from file and return as Byte()
Try
If Not String.IsNullOrEmpty(filename) AndAlso System.IO.File.Exists(filename) Then
Using fs As FileStream = New FileStream(filename, FileMode.Open, FileAccess.Read)
Dim imageBytes(fs.Length) As Byte
'read image from file and put into Byte()
fs.Read(imageBytes, 0, fs.Length)
Return imageBytes
End Using
End If
Catch ex As Exception
Debug.WriteLine("Error (GetImageAsByteArray): " + ex.Message)
Throw
End Try
Return Nothing
End Function
Public Function TblOfficialsExecuteNonQuery(sqlText As String, fullName As String, birthdate As Date, jobDescription As String, term As String, status As String, imageBytes As Byte()) As Integer
Dim rowsAffected As Integer = 0
'create new connection
Using cn As OleDbConnection = New OleDbConnection(_connectionStr)
'open
cn.Open()
'create new instance
Using cmd As OleDbCommand = New OleDbCommand(sqlText, cn)
'OLEDB doesn't use named parameters in SQL. Any names specified will be discarded and replaced with '?'
'However, specifying names in the parameter 'Add' statement can be useful for debugging
'Since OLEDB uses anonymous names, the order which the parameters are added is important
'if a column is referenced more than once in the SQL, then it must be added as a parameter more than once
'parameters must be added in the order that they are specified in the SQL
'if a value is null, the value must be assigned as: DBNull.Value
With cmd.Parameters
.Add("!fullName", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(fullName), DBNull.Value, fullName)
.Add("!birthDate", OleDbType.Date).Value = birthdate
.Add("!jobDescription", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(jobDescription), DBNull.Value, jobDescription)
.Add("!term", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(term), DBNull.Value, term)
.Add("!status", OleDbType.VarChar).Value = If(String.IsNullOrEmpty(status), DBNull.Value, status)
'set size to -1, otherwise it defaults to a maxium of 8000
.Add("!photo", OleDbType.VarBinary, -1).Value = imageBytes
End With
'ToDo: remove the following code that is for debugging
'For Each p As OleDbParameter In cmd.Parameters
'Debug.WriteLine(p.ParameterName & ": " & p.Value.ToString())
'Next
'execute
rowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
Return rowsAffected
End Function
Public Function TblOfficialsGetData() As DataTable
Dim dt As DataTable = New DataTable()
Dim sqlText As String = "SELECT * from Officials"
Try
'create new connection
Using con As OleDbConnection = New OleDbConnection(_connectionStr)
'open
con.Open()
'create new instance
Using cmd As OleDbCommand = New OleDbCommand(sqlText, con)
Using da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
'fill DataTable from database
da.Fill(dt)
End Using
End Using
End Using
Return dt
Catch ex As OleDbException
Debug.WriteLine("Error (TblOfficialsGetData - OleDbException) - " & ex.Message & "(" & sqlText & ")")
Throw ex
Catch ex As Exception
Debug.WriteLine("Error (TblOfficialsGetData) - " & ex.Message & "(" & sqlText & ")")
Throw ex
End Try
End Function
Public Function TblOfficialsInsert(fullName As String, birthdate As Date, jobDescription As String, term As String, status As String, imageBytes As Byte()) As Integer
Dim rowsAffected As Integer = 0
Dim sqlText As String = String.Empty
sqlText = "INSERT INTO Officials ([FullName], [BirthDate], [JobDescription], [Term], [Status], [Photo]) VALUES (?, ?, ?, ?, ?, ?);"
Try
'insert data to database
Return TblOfficialsExecuteNonQuery(sqlText, fullName, birthdate, jobDescription, term, status, imageBytes)
Catch ex As OleDbException
Debug.WriteLine("Error (TblOfficialsInsert - OleDbException) - " & ex.Message & "(" & sqlText & ")")
Throw ex
Catch ex As Exception
Debug.WriteLine("Error (TblOfficialsInsert) - " & ex.Message & "(" & sqlText & ")")
Throw ex
End Try
Return rowsAffected
End Function
Public Function TblOfficialsUpdate(fullName As String, birthdate As Date, jobDescription As String, term As String, status As String, imageBytes As Byte()) As Integer
Dim rowsAffected As Integer = 0
Dim sqlText As String = String.Empty
sqlText = "UPDATE Officials SET [FullName] = ?, [Birthdate] = ? , [JobDescription] = ?, [Term] = ?, [Status] = ?, [Photo] = ?;"
Try
'update data in database
Return TblOfficialsExecuteNonQuery(sqlText, fullName, birthdate, jobDescription, term, status, imageBytes)
Catch ex As OleDbException
Debug.WriteLine("Error (TblOfficialsUpdate - OleDbException) - " & ex.Message & "(" & sqlText & ")")
Throw ex
Catch ex As Exception
Debug.WriteLine("Error (TblOfficialsUpdate) - " & ex.Message & "(" & sqlText & ")")
Throw ex
End Try
Return rowsAffected
End Function
End Class
Usage
Create Access Database:
Private _helper As HelperAccess = Nothing
...
Dim sfd As SaveFileDialog = New SaveFileDialog()
sfd.Filter = "Access Database (*.accdb)|*.accdb|Access Database (*.mdb)|*.mdb"
If sfd.ShowDialog() = DialogResult.OK Then
'create new instance
_helper = New HelperAccess(sfd.FileName)
Dim result As String = _helper.CreateDatabase()
End If
Create Table
Private _helper As HelperAccess = Nothing
...
Dim result As String = _helper.CreateTblOfficials()
Insert data to database:
Private _helper As HelperAccess = Nothing
...
Dim imageBytes As Byte() = Nothing
imageBytes = System.IO.File.ReadAllBytes("C:\Temp\Images\Test1.jpg")
_helper.TblOfficialsInsert("Joe Smith", New Date(1986, 5, 20), "Captain", "2016-2030", "Active", imageBytes)
Get data from database:
Add a DataGridView to your form from the Toolbox (don't add any columns)
Private _dt As DataTable = New DataTable()
Private _helper As HelperAccess = Nothing
Private _source As BindingSource = New BindingSource()
...
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'set properties
DataGridView1.AllowUserToAddRows = False
DataGridView1.AllowUserToDeleteRows = False
'set data source
DataGridView1.DataSource = _source
End Sub
Private Sub GetData()
'get data from database
_dt = _helper.TblOfficialsGetData()
'set value
_source.DataSource = _dt
_source.ResetBindings(True)
End Sub
Resources
CREATE TABLE statement (Microsoft Access SQL)
How can I refresh c# dataGridView after update?
Getting binary data using SqlDataReader

Insert data from VB net into Postgresql

I'm trying to input data from my vb into PostgreSQL
the source is another database on Ms Access
im using this code for connection
Public Function LoadAcces_tblpibconr() As DataTable 'ganti ini sesuai nama table
Dim Table As DataTable = New DataTable()
Command.Connection = conn.OpenConnection()
Command.CommandText = "select * from tblpibconr"
Command.CommandType = CommandType.Text
ReadRows = Command.ExecuteReader()
Table.Load(ReadRows)
ReadRows.Close()
conn.CloseConexion()
Return Table
End Function
'=====================================TABLE POSTGRESQL========================='
Public Function LoadNpgsql_tblpibconr() As DataTable
Dim Table As DataTable = New DataTable()
Cmd.Connection = connNpgsql.OpenConnection()
Cmd.CommandText = "select * from tblpibconr"
Cmd.CommandType = CommandType.Text
ReadRows1 = Cmd.ExecuteReader()
Table.Load(ReadRows1)
ReadRows1.Close()
connNpgsql.CloseConexion()
Return Table
End Function
I'm using this function for filtering the data
I'll compare the data first and take the data without a match and stored it into postgresql
Public Function CekData_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String) As Boolean
Dim Table As DataTable = New DataTable()
Cmd.Connection = connNpgsql.OpenConnection()
If Cmd.Parameters.Count > 0 Then
Cmd.Parameters.Clear()
End If
Cmd.Parameters.AddWithValue("#car", car)
Cmd.Parameters.AddWithValue("#reskd", reskd)
Cmd.Parameters.AddWithValue("#contno", contno)
Cmd.CommandText = <sql>select * from tblpibconr where car=#car and reskd=#reskd and contno=#contno</sql>.Value
Cmd.CommandType = CommandType.Text
ReadRows1 = Cmd.ExecuteReader() 'ERROR System.InvalidOperationException: 'Parameter '#car' must have its value set'
Table.Load(ReadRows1)
ReadRows1.Close()
If Table.Rows.Count > 0 Then
Return False
Else
Return True
End If
Cmd.Parameters.Clear()
connNpgsql.CloseConexion()
End Function
Sub bandingkan_data_tblpibconr()
For i = 0 To DGV1.Rows.Count - 1
Dim validasi = query.CekData_tblpibconr(DGV1.Rows(i).Cells(0).Value, DGV1.Rows(i).Cells(1).Value, DGV1.Rows(i).Cells(2).Value) 'cek data dari access ke postgresql
If validasi = True Then 'jika data di access tidaj ada
'inser data
Dim a As String
If IsDBNull(DGV1.Rows(i).Cells(4).Value.ToString()) Then
a = "0"
Else
a = DGV1.Rows(i).Cells(4).Value.ToString()
End If
DGV1.Rows(i).DefaultCellStyle.BackColor = Color.MistyRose
Dim Insertdata = query.insertNpgsql_tblpibconr(DGV1.Rows(i).Cells(0).Value.ToString(), DGV1.Rows(i).Cells(1).Value.ToString(), DGV1.Rows(i).Cells(2).Value.ToString() _
, DGV1.Rows(i).Cells(3).Value.ToString(), a)
If Insertdata = True Then
' MsgBox("Masuk")
Else
MsgBox("Data Gagal DIMASUKAN")
End If
End If
Next i
LoadNpgsql_tblpibconr()
MsgBox("Selesai")
End Sub
Public Function insertNpgsql_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String, ByVal contukur As String, ByVal conttipe As String) As Boolean
Cmd.Connection = connNpgsql.OpenConnection()
If Cmd.Parameters.Count = 0 Then
Cmd.Parameters.Clear()
End If
Try
Cmd.CommandText = "insert into tblpibconr(car,reskd,contno,contukur,conttipe) values(#car,#reskd,#contno,#contukur,#conttipe)"
Cmd.CommandType = CommandType.Text
Cmd.Parameters.AddWithValue("#car", car)
Cmd.Parameters.AddWithValue("#reskd", reskd)
Cmd.Parameters.AddWithValue("#contno", contno)
Cmd.Parameters.AddWithValue("#contukur", contukur)
Cmd.Parameters.AddWithValue("#conttipe", conttipe)
Cmd.ExecuteNonQuery()
str = "insert into tblpibconr(car,reskd,contno,contukur,conttipe) values(#car , #reskd , #contno, #contukur, #conttipe)"
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
connNpgsql.CloseConexion()
End Function
this is the error that I get
System.InvalidOperationException: 'Parameter '#car' must have its
value set'
ITS Refer to ReadRows1 = Cmd.ExecuteReader() on function cekdata_tblpibconr and Dim validasi = query.CekData_tblpibconr(DGV1.Rows(i).Cells(0).Value, DGV1.Rows(i).Cells(1).Value, DGV1.Rows(i).Cells(2).Value) on sub bandingkan_data_tblpibconr
but this error appear after the data successfully inserted to my Postgresql
Before running the Function where the error occurred, I have checked if we really have a value for car.
This method demonstrates what I mean by keeping your database objects local. The connection and command are created locally in a Using block. They will be closed and disposed even it there is an error.
You can pass the connection string directly to the constructor of the connection. Likewise, pass the command text and the connection to the constructor of the command. The default CommandType is CommandType.Text so it is not necessary to explicitly set that property.
Open the connection at the last possible moment directly before the command is executed.
Public Function CekData_tblpibconr(ByVal car As String, ByVal reskd As String, ByVal contno As String) As Boolean
If String.IsNullOrEmpty(car) Then
MessageBox.Show("Car has no value")
Return True '??
End If
Dim Table As DataTable = New DataTable()
Using cn As New NpgsqlConnection(ConStr),
cmd As New NpgsqlCommand("select * from tblpibconr where car=#car and reskd=#reskd and contno=#contno;", cn)
cmd.Parameters.Add("#car", NpgsqlDbType.Varchar).Value = car
cmd.Parameters.Add("#reskd", NpgsqlDbType.Varchar).Value = reskd
cmd.Parameters.Add("#contno", NpgsqlDbType.Varchar).Value = contno
cn.Open()
Table.Load(cmd.ExecuteReader)
End Using
If Table.Rows.Count > 0 Then
Return False
Else
Return True
End If
End Function

Invalid column name when run from vb.net

I've facing this "invalid column name" error when I try to run my vb.net code. This vb.net will pass some parameters to a stored procedure. But when I try to execute the stored procedure from SQL server management studio, it works.
Below is my code:
LoadData("tbl_Sources", "sPlayerID,'',sPlayerName", "tbl_Dest", "dPlayerID,"",dPlayerName")
------------------------------------------
Public Function LoadData(ByVal frmTblname As String, ByVal frmClmnName As String, ByVal toTblName As String, ByVal toClmnName As String) As Integer
Dim con As New SqlClient.SqlConnection
Dim conManager As New Connection
Dim sqlParams() As SqlParameter = New SqlParameter() { _
New SqlParameter("#fromTable", SqlDbType.NVarChar, 50) With {.Value = frmTblname}, _
New SqlParameter("#fromColumn", SqlDbType.Structured, 4000) With {.Value = "'" + frmClmnName + "'"}, _
New SqlParameter("#toTable", SqlDbType.NVarChar, 50) With {.Value = toTblName}, _
New SqlParameter("#toColumn", SqlDbType.NVarChar, 4000) With {.Value = "'" + toClmnName + "'"} _
}
Dim err As Integer
con = conManager.GetConnection(sConn)
err = ConnectionExec.RunSPReturnInteger(con, "insertUnknownDir", sqlParams)
Return err
End Function
---------------------------------------------------------
Public Function RunSPReturnInteger(ByVal con As SqlClient.SqlConnection, ByVal strSP As String, ByVal ParamArray commandParameters() As SqlClient.SqlParameter) As Integer
Dim retVal As Integer
LogManager.WriteLog("#################################### Start " + strSP + " ####################################")
Try
Dim cmd As New SqlCommand(strSP, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandTimeout = 0
Dim p As SqlClient.SqlParameter
For Each p In commandParameters
p = cmd.Parameters.Add(p)
p.Direction = ParameterDirection.Input
p.SqlDbType = SqlDbType.Structured
Next
retVal = cmd.ExecuteNonQuery()
cmd.Dispose()
Return retVal
LogManager.WriteLog("Try RunSPReturnInteger 1 -> SP Name : " + strSP + " > " + retVal.ToString)
Catch ex As Exception
'MsgBox(ex.Message)
LogManager.WriteLog("Catch RunSPReturnInteger 1-> SP Name : " + strSP + ">> " + ex.Message)
Throw New Exception(ex.Message, ex)
Return -1
End Try
End Function
And here is my store procedure:
ALTER procedure [dbo].[insertUnknownDir] #fromTable nvarchar(50),#fromColumn nvarchar(4000),#toTable nvarchar(50),#toColumn nvarchar(4000)
as
begin
declare #Query nvarchar(4000) print 'exec [insertUnknownDir] '+#fromTable+' ,'+#fromColumn+' ,'+#toTable+','+#toColumn+''
SET #Query ='INSERT INTO ['+#toTable+']('+#toColumn+')
SELECT TOP 15 '+#fromColumn+'
FROM '+#fromTable+'
WHERE profile.sPlayerID = '+#fromTable+'.sPlayerID'
exec sp_executesql #Query
END
Any advice/help is appreciated!
Since you use dynamic SQL there may be a combination of parameters that fail.
It is better to run SQL Profiler to catch the SQL statements executed on a specific database to see the exact SQL query that caused error

VB get cursor that returns a function in postgresql

I am using postgresql and vb, and I want to obtner in vb the result of a function that returns a cursor, but I have only been able to make it return the name of the cursor, and I do not want that, but the cursor data.
This is the code :
Sub BUSQUEDA(ByRef OBJ As Object, ByVal STR_VALOR As String, ByVal INT_TIPO As Integer, ByVal STR_OPERACION As String)
Dim CONECTION As New OdbcConnection
Try
CONECTION.ConnectionString = ConfigurationManager.ConnectionStrings("SEAU.My.MySettings.FARMACIA_ISABEL_DBConnectionString_64").ConnectionString + ";pwd=xxxxx"
Dim COMMAND As OdbcCommand = New OdbcCommand(" SELECT SP_BUSQUEDA_DGV('" + STR_VALOR + "'," + CStr(INT_TIPO) + ",'" + STR_OPERACION + "','CURSOR_BUSQ'); " +
" FETCH ALL IN ""CURSOR_BUSQ"";", CONECTION)
Dim DA As New OdbcDataAdapter
Dim DT As New DataTable
CONECTION.Open()
DA.SelectCommand = COMMAND
DA.Fill(DT)
OBJ = DT
CONECTION.Close()
Catch ex As Exception
If (CONECTION.State = ConnectionState.Open) Then
CONECTION.Close()
End If
Throw ex
End Try
End Sub
I'd appreciate your help

Update statment using vb.net to update all fields

I create table using sql developer
create table tablenodes
(
nodeNo int ,
nodeName varchar2(50),
centerX int ,
centerY int,
radius number(7,2),
fileNo int
)
And I want to update all fields in this table, so I wrote the following code:
Friend Function UpdateNodeToTable(ByVal FN As Integer, ByVal nd As classNode) As Boolean
Try
Dim con As New OracleConnection
con.ConnectionString = "Persist Security Info=False;User ID=manal;password=manal;Data Source=xe"
con.Open()
Dim cmd As New OracleCommand
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.CommandText = "update tablenodes set nodeName=#NodeName, centerX = #NodeCenterX," & _
"centerY= #NodeCenterY , radius= #NodeRadius where nodeNo= #nodeNum and fileno= #FileNum"
cmd.Parameters.Add("#NodeNum", OracleDbType.Int32).Value = nd.pID
cmd.Parameters.Add("#NodeName", OracleDbType.Varchar2).Value = nd.pName
cmd.Parameters.Add("#NodeCenterX", OracleDbType.Int32).Value = nd.pCenter.X
cmd.Parameters.Add("#NodeCenterY", OracleDbType.Int32).Value = nd.pCenter.Y
cmd.Parameters.Add("#NodeRadius", OracleDbType.Double).Value = nd.pRadius
cmd.Parameters.Add("#FileNum", OracleDbType.Int32).Value = FN
Dim success As Boolean
If cmd.ExecuteNonQuery() = 1 Then
success = True
Else
success = False
End If
cmd.Dispose()
con.Close()
con.Dispose()
Return success
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Function
I have a problem in updating statements, can't write it correctly, every time I try to edit it, gives me different error (ora-01036 illegal variable name/number, missing expression, invalid identifier).
The bind variables in you UPDATE statement should be prefixed by a colon, not the # symbol
cmd.CommandText = "update tablenodes set nodeName=:NodeName, centerX = :NodeCenterX," & _
"centerY= :NodeCenterY , radius= :NodeRadius where nodeNo= :nodeNum and fileno= :FileNum"
And there would be no prefix what you're setting the parameters
cmd.Parameters.Add("NodeNum", OracleDbType.Int32).Value = nd.pID
cmd.Parameters.Add("NodeName", OracleDbType.Varchar2).Value = nd.pName
cmd.Parameters.Add("NodeCenterX", OracleDbType.Int32).Value = nd.pCenter.X
cmd.Parameters.Add("NodeCenterY", OracleDbType.Int32).Value = nd.pCenter.Y
cmd.Parameters.Add("NodeRadius", OracleDbType.Double).Value = nd.pRadius
cmd.Parameters.Add("FileNum", OracleDbType.Int32).Value = FN