Showing posts with label creating. Show all posts
Showing posts with label creating. Show all posts

Friday, March 23, 2012

Executing a Stored Procedure in a loop

Hi There!

I need to execute a stored procedure for each row returned from a Select statement for now the only way for me to do it is by creating a cursor and loop thought the result and passing the parameters for the stored procedure and call it in the loop.

My question is. Is there any way I can put the 'execute [spStoredProcedure] param1, param2' with in the select statement so I won't need to create a cursor and manually call the stored procedure for each record?

Hi Lazer,

If you're using 2000, have you had a look at functions? EG:

select fn_MyFunction(a.Column1)

from MyTable

where something = something

Or, if using 2005, have you had a look at CROSS/OUTER APPLY?

select *

from MyTable a t

cross apply fn_MyFunction(t.Column1) as b

The difference being that cross/outer apply must be a table valued function...

Cheers

Rob

|||

Hi Rob,

i using 2000, i want to show a record set for user with the data only have monday date. even the date in database is not monday but i would like to take the early monday date. so can i have a sample how this loop function work?

select fn_MyFunction(a.dtanswerdate)

from answer

where something = something

if i want to update or change the date into monday date for display.

regards

terence chua

Executing a Stored Procedure in a loop

Hi There!

I need to execute a stored procedure for each row returned from a Select statement for now the only way for me to do it is by creating a cursor and loop thought the result and passing the parameters for the stored procedure and call it in the loop.

My question is. Is there any way I can put the 'execute [spStoredProcedure] param1, param2' with in the select statement so I won't need to create a cursor and manually call the stored procedure for each record?

Hi Lazer,

If you're using 2000, have you had a look at functions? EG:

select fn_MyFunction(a.Column1)

from MyTable

where something = something

Or, if using 2005, have you had a look at CROSS/OUTER APPLY?

select *

from MyTable a t

cross apply fn_MyFunction(t.Column1) as b

The difference being that cross/outer apply must be a table valued function...

Cheers

Rob

|||

Hi Rob,

i using 2000, i want to show a record set for user with the data only have monday date. even the date in database is not monday but i would like to take the early monday date. so can i have a sample how this loop function work?

select fn_MyFunction(a.dtanswerdate)

from answer

where something = something

if i want to update or change the date into monday date for display.

regards

terence chua

Executing a stored procedure

How do you execute a stored procedure after creating it
with a script.CREATE PROCEDURE blah
AS
BEGIN
.. do stuff ...
END
GO
EXEC blah
GO
http://www.aspfaq.com/
(Reverse address to reply.)
"Aboki" <hcokoli@.yahoo.com> wrote in message
news:210401c46ff7$77e750f0$a501280a@.phx.gbl...
> How do you execute a stored procedure after creating it
> with a script.|||EXEC <proc_name> [value1ofparm1],
[value2ofparm2], ...
go
"Aboki" wrote:

> How do you execute a stored procedure after creating it
> with a script.
>

Executing a stored procedure

How do you execute a stored procedure after creating it
with a script.
CREATE PROCEDURE blah
AS
BEGIN
... do stuff ...
END
GO
EXEC blah
GO
http://www.aspfaq.com/
(Reverse address to reply.)
"Aboki" <hcokoli@.yahoo.com> wrote in message
news:210401c46ff7$77e750f0$a501280a@.phx.gbl...
> How do you execute a stored procedure after creating it
> with a script.
|||EXEC <proc_name> [value1ofparm1],
[value2ofparm2], ...
go
"Aboki" wrote:

> How do you execute a stored procedure after creating it
> with a script.
>
sql

Executing a stored procedure

How do you execute a stored procedure after creating it
with a script.CREATE PROCEDURE blah
AS
BEGIN
... do stuff ...
END
GO
EXEC blah
GO
--
http://www.aspfaq.com/
(Reverse address to reply.)
"Aboki" <hcokoli@.yahoo.com> wrote in message
news:210401c46ff7$77e750f0$a501280a@.phx.gbl...
> How do you execute a stored procedure after creating it
> with a script.

Executing A No. of queries thru another query

Dear Sir,

My database have a no. of tables. I have created separate sql files for different tables. Now i want to create all the tables by creating another sql file which will contain the individual sql files.

for example

USE DealSoft

EXEC("c:\SQLAccountTypes.sql")

EXEC("c:\\SQLAccounts.sql")

EXEC("c:\\SQLParties.sql")

EXEC command doesn't work this way. can u suggest the proper syntax.

with regards

wilfi

You could use xp_cmdshell for execute any external program and you could run osql script.sql from command line.

As result you could run:

Code Snippet

xp_cmdshell 'osql C:\yourScript.sql'

or (only in SQL Server 2005)

Code Snippet

xp_cmdshell 'sqlcmd C:\youScript.sql'

May be you need to configure account for executing external apps. You could use sp_xp_cmdshell_proxy_account stored procedure

|||

Wilfi,

If using SQL Server 2005, you might want to consider creating an SSIS package to perform such an action. With SQL Server 2000 that solution becomes "using a DTS package."

Another aspect of this matter would be to put your SQL scripts into stored procedures. You can have one stored procedure invoke multiple other stored procedures, similar to the BATCH action you have described. This plan works for any version of SQL Server, as far as I know.

Dan

|||

Dear Dan,

I would like to invoke my individual Stored Procedures thru a Master S.P. as suggested by you.

Can u tell me the syntax for the same with a small example(of Master S.P.).

thanking U.

With Regards,

wilfi

|||

Code Snippet

--Create procedures

CREATE PROCEDURE mySp1
as
BEGIN
PRINT 'Call To MySP1'
END
go


CREATE PROCEDURE mySp2
as
BEGIN
PRINT 'Call to MySP2'
END
go

CREATE PROCEDURE myMasterSP
as
BEGIN
EXEC mySP1
EXEC mySP2
END
go

-- Execute Master SP, you could do it any time after creating

myMasterSP

|||

Dear Sir,

Hearty Thanx for the immediate response. I could do as suggested by u.

with regards,

wilfi

|||

Konstantin,

Thanks! You beat me to it! ;-)

Dan

|||

Hey Konstantin, i was lookin for something related to inline store procs and saw your post..

do you know if those 2 last procs : mySP1 and mySP2 run async.

meaning, does the mySP2 proc waits for the mySP1 to be completed?.

It will be very helpful if you know!

anyways thanks in advance

Dave.

|||

Dave,

Sorry for butting in. All my experiences are that they run sequentially, in the order listed in the SP.

I would have all kinds of wrong answers in my computations were that not so.

Dan

|||

mySp1 and mySp2 run sync. Meaning the mySp2 wait for the mySp1 to be completed.

If you need async call, you could emulate this approach by using SQL Server Broker

Executing A No. of queries thru another query

Dear Sir,

My database have a no. of tables. I have created separate sql files for different tables. Now i want to create all the tables by creating another sql file which will contain the individual sql files.

for example

USE DealSoft

EXEC("c:\SQLAccountTypes.sql")

EXEC("c:\\SQLAccounts.sql")

EXEC("c:\\SQLParties.sql")

EXEC command doesn't work this way. can u suggest the proper syntax.

with regards

wilfi

You could use xp_cmdshell for execute any external program and you could run osql script.sql from command line.

As result you could run:

Code Snippet

xp_cmdshell 'osql C:\yourScript.sql'

or (only in SQL Server 2005)

Code Snippet

xp_cmdshell 'sqlcmd C:\youScript.sql'

May be you need to configure account for executing external apps. You could use sp_xp_cmdshell_proxy_account stored procedure

|||

Wilfi,

If using SQL Server 2005, you might want to consider creating an SSIS package to perform such an action. With SQL Server 2000 that solution becomes "using a DTS package."

Another aspect of this matter would be to put your SQL scripts into stored procedures. You can have one stored procedure invoke multiple other stored procedures, similar to the BATCH action you have described. This plan works for any version of SQL Server, as far as I know.

Dan

|||

Dear Dan,

I would like to invoke my individual Stored Procedures thru a Master S.P. as suggested by you.

Can u tell me the syntax for the same with a small example(of Master S.P.).

thanking U.

With Regards,

wilfi

|||

Code Snippet

--Create procedures

CREATE PROCEDURE mySp1
as
BEGIN
PRINT 'Call To MySP1'
END
go


CREATE PROCEDURE mySp2
as
BEGIN
PRINT 'Call to MySP2'
END
go

CREATE PROCEDURE myMasterSP
as
BEGIN
EXEC mySP1
EXEC mySP2
END
go

-- Execute Master SP, you could do it any time after creating

myMasterSP

|||

Dear Sir,

Hearty Thanx for the immediate response. I could do as suggested by u.

with regards,

wilfi

|||

Konstantin,

Thanks! You beat me to it! ;-)

Dan

|||

Hey Konstantin, i was lookin for something related to inline store procs and saw your post..

do you know if those 2 last procs : mySP1 and mySP2 run async.

meaning, does the mySP2 proc waits for the mySP1 to be completed?.

It will be very helpful if you know!

anyways thanks in advance

Dave.

|||

Dave,

Sorry for butting in. All my experiences are that they run sequentially, in the order listed in the SP.

I would have all kinds of wrong answers in my computations were that not so.

Dan

|||

mySp1 and mySp2 run sync. Meaning the mySp2 wait for the mySp1 to be completed.

If you need async call, you could emulate this approach by using SQL Server Broker

Wednesday, March 21, 2012

Executing .sql file from vb.net

Hi,

I have a .sql file that contains sql statement to create tables. Is there a way where I can execute the codes in this file creating the tables?

Thanks

EDIT

The code is in C# so use the code converter in the second link.

http://www.c-sharpcorner.com/UploadFile/mahesh/CreatingDBProgrammaticallyMCB11282005064852AM/CreatingDBProgrammaticallyMCB.aspx

http://www.carlosag.net/Tools/CodeTranslator/Default.aspx

|||

Hi,

Thanks for the link. Will try it out and post the outcome.

|||If it does not work it will be related to C# to VB conversion because I have helped a user clone a database and all the objects with ExecuteNonQuery.|||

Hi,

Yup the 'ExecuteSQL' did not seem to work, so I just removed that entire function and directly called an 'ExecuteNonQuery' and it worked fine.

Thanks!

Executing .sql file from vb.net

Hi,

I have a .sql file that contains sql statement to create tables. Is there a way where I can execute the codes in this file creating the tables?

Thanks

EDIT

The code is in C# so use the code converter in the second link.

http://www.c-sharpcorner.com/UploadFile/mahesh/CreatingDBProgrammaticallyMCB11282005064852AM/CreatingDBProgrammaticallyMCB.aspx

http://www.carlosag.net/Tools/CodeTranslator/Default.aspx

|||

Hi,

Thanks for the link. Will try it out and post the outcome.

|||If it does not work it will be related to C# to VB conversion because I have helped a user clone a database and all the objects with ExecuteNonQuery.|||

Hi,

Yup the 'ExecuteSQL' did not seem to work, so I just removed that entire function and directly called an 'ExecuteNonQuery' and it worked fine.

Thanks!

sql

Monday, March 19, 2012

ExecuteNonQuery: Connection property has not been initialized

I am trying to create a web form that will be used to create new users. The
first step that I am taking is creating a web form that can check the
username against a database to see if it already exists. I would it to do
this on the fly, if possible. When I execute my current code, I get the
following error:

ExecuteNonQuery: Connection property has not been initialized

Below is the code from the page itself:
--
<!-- #INCLUDE FILE="../include/context.inc" -->
<!-- #INCLUDE FILE="../include/db_access.inc" --
<script language="VB" runat="server"
Sub CheckButton_Click(Sender as Object, e as EventArgs)

Dim result As Int32
Dim cmd As OdbcCommand

cmd = new OdbcCommand( "(? = CALL CheckUserExists(?))", db_conn )
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add( "result", OdbcType.Int ).Direction =
ParameterDirection.ReturnValue

cmd.Parameters.Add( "@.userName", OdbcType.VarChar, 100 ).Value =
Request.Form("userName")

cmd.ExecuteNonQuery()
result = cmd.Parameters("result").Value

If result <> 1 Then
CheckResults.Text="<font color=""#ff0000"">Username already
exists!</font>"
Else
CheckResults.Text="<font color=""#009900"">Username is
available.</font>"
End If

end Sub

</script
<html><body>
<form runat="server">
<asp:TextBox id=userName runat="server" />
<asp:Button id=CheckButton runat="server" Text="Check Username"
onClick="CheckButton_Click" /
<p>
<asp:Label id=CheckResults runat=server />
</form>
</body></html>
--

Can anyone see why I might get this error? Here are some more details of
the error:

Line 15: cmd.Parameters.Add( "@.userName", OdbcType.VarChar, 100 ).Value =
Request.Form("userName")
Line 16:
*Line 17: cmd.ExecuteNonQuery()
Line 18: result = cmd.Parameters("result").Value

Thank You,
Jason WilliardHi Jason,

To me it seems that you are still using asp type techniques of data access. You will have to initate your dbconnection object before you can actually use any database related functions.

With your code you are missing ofdb_conn variable. Which I am presuming that you have in include file, but this will not work with asp.net.

HTH|||It's looks like your maye be geeting error because of following reason.

1.Your connection string is not correct or not open as we can't see when and where it was intialize/open .
2.check your store procdure and see if you are passing correct parameter,correct typen etc.
3.In your code it looks likes may be you have open your connection in db_access.inc but i don't think it's good approach .you should open the connection in same sub and close as soon as you you finished.Or if you want to write neat and clean code and also don't want to wire same code agaian then create data layer class where you can perform all the database realted operation.

Arvind Malik|||I made some changes to the page so that the db connection is all done from within the Sub. Below are the code changes that I made:

--
Sub CheckButton_Click(Sender as Object, e as EventArgs)

Dim db_conn_str As String
Dim db_conn As OdbcConnection
Dim resultAs Int32
Dim cmdAs OdbcCommand
Dim context_dsn_nameAs String = "adwarefilter"

db_conn_str = "dsn=" & context_dsn_name & ";"
db_conn = New OdbcConnection( db_conn_str )
db_conn.Open()

cmd = new OdbcCommand( "(? = CALL CheckUserExists(?))", db_conn )
cmd.CommandType = CommandType.StoredProcedure
--

Now I am getting a new error message:

--
Exception Details: System.Data.Odbc.OdbcException: ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Line 1: Incorrect syntax near '='.

Source Error:

Line 28: cmd.Parameters.Add( "@.username", OdbcType.VarChar, 100 ).Value = Request.Form("userName")
Line 29:
Line 30: cmd.ExecuteNonQuery()
--

Any suggestions?|||What is this query: "(? = CALL CheckUserExists(?))", ? Where is the SQL Query?

Brian|||This is a call to a Stored Procedure. The SQL query is within the Stored Proc.|||I am pretty sure that your stored procedure call should look like this:


cmd = new OdbcCommand( "{CALL CheckUserExists(?)}", db_conn )

Note that I made these changes:
-- removed the question mark (?) and the equal sign (=)
-- changed a set of parentheses to a set of curly braces

But, I have a question -- why oh why are you using the System.Data.Odbc class instead of System.Data.SqlData? Are you using SQL Server 7?

Terri|||Actually, I hadn't noticed you are using a ReturnValue, sorry!! The question mark and equal sign can remain. The problem is likely just the use of parentheses instead of curly braces.


cmd = new OdbcCommand( "{? =CALL CheckUserExists(?)}", db_conn )

Terri

Friday, February 24, 2012

EXECUTE permission denied on [various DB objects] within SQL Express db

First attempt at using SQL Express developing web app. All works fine within VS2005 dev web server. However, after compiling and creating IIS7 site on same machine without changingconnectionString="Server=xxxx\SQLEXPVISTA;Database=ABCtest;Integrated Security=true" (SQLVISTA is named instance of SQL Express)

The only easy way I can avoid the 'EXECTUTE permissions denied...' is to give the NT AUTHORITY\NETWORK SERVICE db_owner role membership. Should I worry? Or should I go through the objects individually and specify permissions? Eventually, this will be on public web server.

In advance, thanks.

ASM

Hi,

From your description, it seems that you met "'EXECTUTE permissions denied..." error when you are trying to run your application from your IIS, right?

Based on my understanding, the cause of the issue is the account of IIS has not the permission to access your database. Generally, the ASPNET account is be authorized by default in your SQLExpress, so your application should work while running from the development server of VisualStudio. But when you deploy your application into IIS, the login account has changed, so you should add the login account into the logins of SQLExpress.

Thanks.