Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

VB.net convert a sql stored procedure to code in application

Posted on 2009-05-06
23
Medium Priority
?
512 Views
Last Modified: 2013-11-26
Thanks in advance experts.  I am still learning (im discovering self teaching programming skills is not easy), so any code examples would be great - I currently have written a program that deletes a user from a sql 2000 table.  To do this I have to delete some additional linked data first.  I have a stored procedure I call that does the work.  This works great.  The problem is I have more than 60 sql servers across the country that I will have to create this stored procedure on. I can think of three ways to tackle this.  1) Create the stored procedure (not something I want to do) 2) create it programmatically when my app runs (I just dont know how to do that) 3) convert the stored procedure into code directly in my app. & any help would be great . As our server count will continue to grow, I would like to have the code in my app and not use the stored procedure. I just do not know how to do that.  I have attached the code for the stored procedure and my vb code  thanks again
Stored procedure - - - - 
CREATE PROCEDURE Delete_Users
@UserID varchar(50)
AS
delete from TParkUnit_TNotificationProfile where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID)) 
delete from TNotificationProfile_TNotificationMedia where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID)) 
delete from TEventCode_TNotificationProfile where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID)) 
delete from TNotificationProfile where userid=(select UserId from TUser where UserInitials = @UserID)
 
delete from TMaintenanceProcess where userid=(select UserId from TUser where UserInitials = @UserID)
 
delete from TWebCustomPosition where userid=(select UserId from TUser where UserInitials = @UserID)
 
delete from TUser_TReportProfile where userid=(select UserId from TUser where UserInitials = @UserID)
 
delete from TUser where UserInitials = @UserID
GO
---------------------------------------------------------
My VB code
 
 Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim con As New OleDb.OleDbConnection
        Dim dbProvider As String
        Dim da As New OleDb.OleDbDataAdapter
        Dim ds As New DataSet
        Dim sql As String
        Dim cb As New OleDb.OleDbCommandBuilder(da)
        Dim Server As String
 
        Dim UserInit As String = txtUserInit.Text
 
        Server = txtIPAddress.Text
        dbProvider = "provider = sqloledb;Data Source=" & Server & ";Initial Catalog=Windman;User ID=user;Password=password"
        sql = "Delete_Users"
        con = New OleDb.OleDbConnection(dbProvider)
        con.Open()
        Dim cmd As New System.Data.OleDb.OleDbCommand("Delete_Users", con)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue(String.Empty, UserInit)
 
 
        If con.State <> ConnectionState.Open Then
            con.Open()
        End If
 
        If cmd.ExecuteNonQuery() < 1 Then
 
        End If
 
        con.Close()
 
        MsgBox("User Deleted")
    End Sub

Open in new window

0
Comment
Question by:NCSA SCADA
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 12
  • 11
23 Comments
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 24316723
Creating the stored procedure through a script or through your application will be better than pulling all those DELETE statements into your VB.



SqlCommand cmCreateMyProcedure = new SqlCommand(MyConnection)
cmCreateMyProcedure.CommandText = "Create Procedure 
 AND the rest of the procedure as you pasted it in
"
 
cmCreateMyProcedure.ExecuteNonQuery();

Open in new window

0
 

Author Comment

by:NCSA SCADA
ID: 24317148
will this work for both sql 2k and 2k5
0
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 24317370
Yes, it will. And SQL7 and SQL 2008.

Probably would be best to do a check whether it already exists:


cmCreateMyProcedure.CommandText = "If not exists (Select * from sysobjects where xtype = 'p' and name = 'Delete_Users') " & _
" Create Procedure  Delete_Users " & _
" @UserID varchar(50) " & _
" AS " & _
" delete from TParkUnit_TNotificationProfile where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
" delete from TNotificationProfile_TNotificationMedia where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
" delete from TEventCode_TNotificationProfile where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
" delete from TNotificationProfile where userid=(select UserId from TUser where UserInitials = @UserID) " & _ 
" delete from TMaintenanceProcess where userid=(select UserId from TUser where UserInitials = @UserID) " & _ 
" delete from TWebCustomPosition where userid=(select UserId from TUser where UserInitials = @UserID) " & _ 
" delete from TUser_TReportProfile where userid=(select UserId from TUser where UserInitials = @UserID) " & _ 
" delete from TUser where UserInitials = @UserID"

Open in new window

0
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 24317377
That way you get to keep the performance and transactionality of your stored procedure.
0
 

Author Comment

by:NCSA SCADA
ID: 24317393
I think I am missing somthing - im not sure how to take my connection and build with the code you posted - sorry for the newbie response, but could use my defined variables and give an example of the connection/sql command ect.  - - - thanks so much for your help
0
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 24317454
Are you always using SQL Server?  If so, do you mind if I change the code to the SQL data provider instead of OleDB?
0
 

Author Comment

by:NCSA SCADA
ID: 24317500
it is always sql, and I do not mind at all - As I was trying to learn this stuff it is likely that i have picked some less than efficient ways of coding - any pointers are most appreciated - thanks
0
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 24317733
using http://connectionstrings.com/sql-server-2005#1 for the connection string ...


 Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim con As New SqlClient.SqlConnection
        Dim dbProvider As String
        Dim sql As String
        Dim Server As String
 
        Dim UserInit As String = txtUserInit.Text
 
        Static bProcCreated as Boolean 'so we don't call the CREATE PROCEDURE block quite so often
 
        Server = txtIPAddress.Text
        dbProvider = "Server=" & Server & ";Datbase=Windman;User ID=user;Password=password;Trusted_Connection=False;"
        con = New SqlClient.SqlConnection(dbProvider)
        con.Open()
 
        If not bProcCreated then
dim cmCreateMyProcedure as SqlCommand
cmCreateMyProcedure = new SqlCommand(MyConnection)
cmCreateMyProcedure.CommandText = "If not exists (Select * from sysobjects where xtype = 'p' and name = 'Delete_Users') " & _
" Create Procedure  Delete_Users " & _
" @UserID varchar(50) " & _
" AS " & _
" delete from TParkUnit_TNotificationProfile where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
" delete from TNotificationProfile_TNotificationMedia where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
" delete from TEventCode_TNotificationProfile where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
" delete from TNotificationProfile where userid=(select UserId from TUser where UserInitials = @UserID) " & _ 
" delete from TMaintenanceProcess where userid=(select UserId from TUser where UserInitials = @UserID) " & _ 
" delete from TWebCustomPosition where userid=(select UserId from TUser where UserInitials = @UserID) " & _ 
" delete from TUser_TReportProfile where userid=(select UserId from TUser where UserInitials = @UserID) " & _ 
" delete from TUser where UserInitials = @UserID"
 
cmCreateMyProcedure.ExecuteNonQuery();
           bProcCreated=true
        end if
 
        sql = "Delete_Users"
        Dim cmd As New System.Data.SqlClient.SqlCommand("Delete_Users", con)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue(String.Empty, UserInit)
 
 
        If con.State <> ConnectionState.Open Then
            con.Open()
        End If
 
        If cmd.ExecuteNonQuery() < 1 Then
 
        End If
 
        con.Close()
 
        MsgBox("User Deleted")
    End Sub

Open in new window

0
 

Author Comment

by:NCSA SCADA
ID: 24317806
Thanks so much - not sure if its a ver thing, but I am getting "type sqlcommand is not defined" . I am using visual studio 2008 - thanks again
0
 

Author Comment

by:NCSA SCADA
ID: 24317994
I figured that out - I do have one more error - cmCreateMyProcedure = New SqlCommand(MyConnection)
errors with MyConnection not defined
0
 

Author Comment

by:NCSA SCADA
ID: 24318188
I think im getting there ... it hangs on this line ..... cmCreateMyProcedure.ExecuteNonQuery() with this error ....... ExecuteNonQuery: Connection property has not been initialized. - I have attached the code as I am using it .... note the changes that I asked about in the last two messages - thanks
Imports System.Data.SqlClient
Public Class Form1
 
 
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim con As New SqlClient.SqlConnection
        Dim dbProvider As String
        Dim Server As String
 
        Static bProcCreated As Boolean 'so we don't call the CREATE PROCEDURE block quite so often
        Server = "10.106.3.220"
        dbProvider = "Server=" & Server & ";Database=Windman;User ID=user;Password=password;Trusted_Connection=False;"
        con = New SqlClient.SqlConnection(dbProvider)
        con.Open()
 
        If Not bProcCreated Then
            Dim cmCreateMyProcedure As SqlCommand
            cmCreateMyProcedure = New SqlCommand(dbProvider)
            cmCreateMyProcedure.CommandText = "If not exists (Select * from sysobjects where xtype = 'p' and name = 'Delete_Users') " & _
            " Create Procedure  Delete_Users " & _
            " @UserID varchar(50) " & _
            " AS " & _
            " delete from TParkUnit_TNotificationProfile where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
            " delete from TNotificationProfile_TNotificationMedia where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
            " delete from TEventCode_TNotificationProfile where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
            " delete from TNotificationProfile where userid=(select UserId from TUser where UserInitials = @UserID) " & _
            " delete from TMaintenanceProcess where userid=(select UserId from TUser where UserInitials = @UserID) " & _
            " delete from TWebCustomPosition where userid=(select UserId from TUser where UserInitials = @UserID) " & _
            " delete from TUser_TReportProfile where userid=(select UserId from TUser where UserInitials = @UserID) " & _
            " delete from TUser where UserInitials = @UserID"
 
            cmCreateMyProcedure.ExecuteNonQuery()
            bProcCreated = True
        End If
 
        
 
    End Sub
End Class

Open in new window

0
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 24318274
change line 19 to
            cmCreateMyProcedure = New SqlCommand(con)

0
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 24318276
Sorry I'm not that good writing the code w/o Intellisense to guide me!
0
 

Author Comment

by:NCSA SCADA
ID: 24318335
made the change i get this error ....... Value of type 'system.Data.SqlClient.SqlConnection cannot be converted to string
0
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 24318488
grr...
cmCreateMyProcedure = New SqlCommand()
cmCreateMyProcedure.Connection = con

Open in new window

0
 

Author Comment

by:NCSA SCADA
ID: 24318673
Well .... you are earning your points today - that worked, but now I am getting an error that says must declare variable @UserID .... the error repeats for each line after the declaration of @UserID .... it looks like some sort of problem with the line above it -  also says incorrect sysntax near the keyword procedure
0
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 24318717
At compile time?  Or runtime?
0
 

Author Comment

by:NCSA SCADA
ID: 24318765
when I click the start debugging arrow
0
 

Author Comment

by:NCSA SCADA
ID: 24319143
any thoughts
0
 
LVL 32

Expert Comment

by:Daniel Wilson
ID: 24319301
please post the entire Button1_click as it now stands.  I'll throw it into VB.Net over here & see if I can find the problem.

thanks.
0
 

Author Comment

by:NCSA SCADA
ID: 24319790
heree ya go - thanks
Imports System.Data.SqlClient
Public Class Form1
 
 
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim con As New SqlClient.SqlConnection
        Dim dbProvider As String
        Dim Server As String
 
 
        Server = "10.106.3.220"
        dbProvider = "Server=" & Server & ";Database=Windman;User ID=user;Password=pass;Trusted_Connection=False;"
        con = New SqlClient.SqlConnection(dbProvider)
        con.Open()
 
 
        Dim cmCreateMyProcedure As SqlCommand
        'cmCreateMyProcedure = New SqlCommand con
        cmCreateMyProcedure = New SqlCommand()
        cmCreateMyProcedure.Connection = con
 
        cmCreateMyProcedure.CommandText = "If not exists (Select * from sysobjects where xtype = 'p' and name = 'Delete_Users') " & _
        " Create Procedure  Delete_Users " & _
        " @UserID varchar(50) " & _
        " AS " & _
        " delete from TParkUnit_TNotificationProfile where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
        " delete from TNotificationProfile_TNotificationMedia where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
        " delete from TEventCode_TNotificationProfile where NotificationProfileId = (select NotificationProfileId from TNotificationProfile where UserId = (select UserId from TUser where UserInitials = @UserID))  " & _
        " delete from TNotificationProfile where userid=(select UserId from TUser where UserInitials = @UserID) " & _
        " delete from TMaintenanceProcess where userid=(select UserId from TUser where UserInitials = @UserID) " & _
        " delete from TWebCustomPosition where userid=(select UserId from TUser where UserInitials = @UserID) " & _
        " delete from TUser_TReportProfile where userid=(select UserId from TUser where UserInitials = @UserID) " & _
        " delete from TUser where UserInitials = @UserID"
 
        cmCreateMyProcedure.ExecuteNonQuery()
 
 
 
        
 
    End Sub
End Class

Open in new window

0
 

Author Comment

by:NCSA SCADA
ID: 24320665
ok - I think i figured it out - seems to work, but it all shows up on one line in the stored procedure ... is there a way to break up the lines so it is easier to read -thanks again
0
 
LVL 32

Accepted Solution

by:
Daniel Wilson earned 2000 total points
ID: 24320766
Yeah, that's annoying.

Change & _
 to & vbcrlf & _
where the line continuation occurs. That will insert a newline character.
0

Featured Post

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question