• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 525
  • Last Modified:

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

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
NCSA SCADA
Asked:
NCSA SCADA
  • 12
  • 11
1 Solution
 
Daniel WilsonCommented:
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
 
NCSA SCADAAuthor Commented:
will this work for both sql 2k and 2k5
0
 
Daniel WilsonCommented:
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
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Daniel WilsonCommented:
That way you get to keep the performance and transactionality of your stored procedure.
0
 
NCSA SCADAAuthor Commented:
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
 
Daniel WilsonCommented:
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
 
NCSA SCADAAuthor Commented:
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
 
Daniel WilsonCommented:
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
 
NCSA SCADAAuthor Commented:
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
 
NCSA SCADAAuthor Commented:
I figured that out - I do have one more error - cmCreateMyProcedure = New SqlCommand(MyConnection)
errors with MyConnection not defined
0
 
NCSA SCADAAuthor Commented:
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
 
Daniel WilsonCommented:
change line 19 to
            cmCreateMyProcedure = New SqlCommand(con)

0
 
Daniel WilsonCommented:
Sorry I'm not that good writing the code w/o Intellisense to guide me!
0
 
NCSA SCADAAuthor Commented:
made the change i get this error ....... Value of type 'system.Data.SqlClient.SqlConnection cannot be converted to string
0
 
Daniel WilsonCommented:
grr...
cmCreateMyProcedure = New SqlCommand()
cmCreateMyProcedure.Connection = con

Open in new window

0
 
NCSA SCADAAuthor Commented:
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
 
Daniel WilsonCommented:
At compile time?  Or runtime?
0
 
NCSA SCADAAuthor Commented:
when I click the start debugging arrow
0
 
NCSA SCADAAuthor Commented:
any thoughts
0
 
Daniel WilsonCommented:
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
 
NCSA SCADAAuthor Commented:
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
 
NCSA SCADAAuthor Commented:
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
 
Daniel WilsonCommented:
Yeah, that's annoying.

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

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 12
  • 11
Tackle projects and never again get stuck behind a technical roadblock.
Join Now