A Good Stored Proc Template - What Are Your Views?

Apr 18, 2008

Hi,

I'm curious to know what templates/standards you guys use for T-SQL stored procs. I've been using the following standard:




Code Snippet
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = '<proc name>')
BEGIN
DROP Procedure <proc name>
END
GO

CREATE PROCEDURE <proc name>
@parm1,
@parm2
AS
BEGIN TRANSACTION <transactionName>;
BEGIN TRY
--DO WORK HERE
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() as ErrorState,
ERROR_PROCEDURE() as ErrorProcedure,
ERROR_LINE() as ErrorLine,
ERROR_MESSAGE() as ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION <transactionName>;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION <transactionName>;
ELSE

ROLLBACK TRANSACTION <transactionName>;
GO




If you guys have any advice/critisizm, please post it as I'm constantly looking into bettering this as much as possible.

Regards
Michael

View 6 Replies


ADVERTISEMENT

Creating A Stored Proc From A Particular Template?

Mar 16, 2006

Hello,

I'm trying to get to grips with SQL Server 2005.

One of the things I want to do is provide members of my team with a stored procedure template that they can use which has special error handling code in it , etc

I found my way to the template explorer and created a new template that I want to use to create stored procedures in certain circumstances (but not ALL circumstances)

But now I can't figure out how to specify WHICH template to use when creating a stored procedure.

Like, when I click on the Programmability/Stored Procedures node and then right click and select New Stored Procedure... it just uses the Basic Template.. but I'd like to be able to elect to use my alternative template to create the stored proc.

So, what are the correct steps to follow? do i just double click my new template in Template Explorer? And then have to go Query/Specify Values for Template Parameters ? Or what?

If this is the way to do it then it seems very clunky really....

Thanks

View 1 Replies View Related

Good Book For Learning The Stored Proc Language

Jul 12, 2007

Though I have been using SQL Server for some years, it is just recently that I have need to learn how to write SP's. I would like a recommendation for a book that is rich with examples (my best learning style).

Many thanks...

Todd

View 1 Replies View Related

SQL Svr 2005 - Use Same Stored Proc &&amp; Views For 2 Databases?

Jan 10, 2007

I am moving a fairly large app from Access 2003 to C#/SQL Server 2005.

The app has one front end mde, but it has two backend data mdbs, one is used in the US and one in the UK.

The two backend mdb's are identical in structure, but of course the data is different. There are 150 tables or so, and we plan to maintain separate databases after the upgrade.

Now, of course, all of the queries are in the front end, the backend db's contain only tables.

In the new world, I do not want to have to maintain the same views and stored procs in two different SQL Server databases.

Is there a way to have all views and stored procs in one database, but have them draw on the data in the two other databases. There must should be a way to deal with this scenario in SQL Server.

Many thanks
Mike Thomas

View 5 Replies View Related

A Stored Proc To Search All Procs, Views, Triggers And Functions

Jul 20, 2005

I developed a search stored proc that searches all orsome of Procs, Views, Triggers and functions. Would anyone be interestedto see it posted here?Do you have any suggestions about other places, websites forums ...., toshare something I have developed?Thanks you for your response in advancePLease send me emailJoin Bytes! {Remove ### before responding}

View 1 Replies View Related

Bad Proc Template

Jul 28, 2006

There is a base-installed template for a stored procedure called "Create Procedure with CURSOR OUT" which has this snippet:


EXEC <Schema_Name, sysname, Schema_Name>.<Procedure_Name, sysname, Procedure_Name> <@proc_cursor_name, , @sample_procedure_cursor> = <@variable_cursor_name, , @test_cursor_variable> OUTPUT

WHILE (@@FETCH_STATUS = 0)

BEGIN

FETCH NEXT FROM <@variable_cursor_name, , @test_cursor_variable>

PRINT 'put user defined code here'

END
But even after instantiating it - it doesn't work. The "FETCH_STATUS" must be seeded with a prior "FETCH" before it has any meaning. This leads me to ask: (1) how could such a widely circulated template have such a conspicuous error and (2) why doesn't TSQL have a looping mechanism that does not require such awkward FETCH "pre-seeding"?
p.s. How do I insert code into a forum post that is single-spaced, rather than duoble-spaced (like my ugly double-spaced snippet above)

View 1 Replies View Related

Looking For A Good Article About Indexed Views.

Apr 29, 2004

Hello folks!
I'm looking for a good article about Indexed Views.

Cheers!
Rafael

View 1 Replies View Related

Can You Trace Into A Stored Proc? Also Does RAISERROR Terminate The Stored Proc Execution.

Feb 13, 2008

I am working with a large application and am trying to track down a bug. I believe an error that occurs in the stored procedure isbubbling back up to the application and is causing the application not to run. Don't ask why, but we do not have some of the sourcecode that was used to build the application, so I am not able to trace into the code.
So basically I want to examine the stored procedure. If I run the stored procedure through Query Analyzer, I get the following error message:
Msg 2758, Level 16, State 1, Procedure GetPortalSettings, Line 74RAISERROR could not locate entry for error 60002 in sysmessages.
(1 row(s) affected)
(1 row(s) affected)
I don't know if the error message is sufficient enough to cause the application from not running? Does anyone know? If the RAISERROR occursmdiway through the stored procedure, does the stored procedure terminate execution?
Also, Is there a way to trace into a stored procedure through Query Analyzer?
-------------------------------------------As a side note, below is a small portion of my stored proc where the error is being raised:
SELECT  @PortalPermissionValue = isnull(max(PermissionValue),0)FROM Permission, PermissionType, #GroupsWHERE Permission.ResourceId = @PortalIdAND  Permission.PartyId = #Groups.PartyIdAND Permission.PermissionTypeId = PermissionType.PermissionTypeId
IF @PortalPermissionValue = 0BEGIN RAISERROR (60002, 16, 1) return -3END 
 

View 3 Replies View Related

Recompile All Stor Proc And Udf And Views

Oct 1, 2003

Hi ,
what would be correct way to recompile
all user objects ?

Developers working by using alter create and rename on udf and stored procedure, dependecicies window in EM does not repesent correct info.

If I want to see up to date all dependedcies of every user defined object in db

Thank you


Alex

View 5 Replies View Related

Stored Proc - Calling A Remote Stored Proc

Aug 24, 2006

I am having trouble executing a stored procedure on a remote server. On my
local server, I have a linked server setup as follows:
Server1.abcd.myserver.comSQLServer2005,1563

This works fine on my local server:

Select * From [Server1.abcd.myserver.comSQLServer2005,1563].DatabaseName.dbo.TableName

This does not work (Attempting to execute a remote stored proc named 'Data_Add':

Exec [Server1.abcd.myserver.comSQLServer2005,1563].DatabaseName.Data_Add 1,'Hello Moto'

When I attempt to run the above, I get the following error:
Could not locate entry in sysdatabases for database 'Server1.abcd.myserver.comSQLServer2005,1563'.
No entry found with that name. Make sure that the name is entered correctly.

Could anyone shed some light on what I need to do to get this to work?

Thanks - Amos.

View 3 Replies View Related

Stored Proc Question : Why If Exisits...Drop...Create Proc?

Jun 15, 2006

Hi All,Quick question, I have always heard it best practice to check for exist, ifso, drop, then create the proc. I just wanted to know why that's a bestpractice. I am trying to put that theory in place at my work, but they areasking for a good reason to do this before actually implementing. All Icould think of was that so when you're creating a proc you won't get anerror if the procedure already exists, but doesn't it also have to do withCompilation and perhaps Execution. Does anyone have a good argument fordoing stored procs this way? All feedback is appreciated.TIA,~CK

View 3 Replies View Related

Can I Use My Own Stored Procedure Template With SQL2005?

Oct 25, 2007

When I go to create a new stored procedure, function, etc. I get a default template... is there anyway to replace this template with one of my own? One that will already have the important information pre-populated (the stuff I always end up having to type in, like company name, etc.).

View 1 Replies View Related

ASP Cannot Run Stored Proc Until The Web User Has Run The Proc In Query Analyzer

Feb 23, 2007

I have an ASP that has been working fine for several months, but itsuddenly broke. I wonder if windows update has installed some securitypatch that is causing it.The problem is that I am calling a stored procedure via an ASP(classic, not .NET) , but nothing happens. The procedure doesn't work,and I don't get any error messages.I've tried dropping and re-creating the user and permissions, to noavail. If it was a permissions problem, there would be an errormessage. I trace the calls in Profiler, and it has no complaints. Thedatabase is getting the stored proc call.I finally got it to work again, but this is not a viable solution forour production environment:1. response.write the SQL call to the stored procedure from the ASPand copy the text to the clipboard.2. log in to QueryAnalyzer using the same user as used by the ASP.3. paste and run the SQL call to the stored proc in query analyzer.After I have done this, it not only works in Query Analyzer, but thenthe ASP works too. It continues to work, even after I reboot themachine. This is truly bizzare and has us stumped. My hunch is thatwindows update installed something that has created this issue, but Ihave not been able to track it down.

View 1 Replies View Related

Calling A Stored Proc From Within Another Stored Proc

Feb 20, 2003

I have seen this done by viewing code done by a SQL expert and would like to learn this myself. Does anyone have any examples that might help.

I guess I should state my question to the forum !

Is there a way to call a stored proc from within another stored proc?

Thanks In Advance.

Tony

View 1 Replies View Related

Stored Proc Calls Another Stored Proc

Jan 13, 2006

Hi all,

I have a stored procedure "uspX" that calls another stored procedure "uspY" and I need to retrieve the return value from uspY and use it within uspX. Does anyone know the syntax for this?

Thanks for your help!
Cat

View 5 Replies View Related

Calling Stored Proc B From Stored Proc A

Jan 20, 2004

Hi all

I have about 5 stored procedures that, among other things, execute exactly the same SELECT statement

Instead of copying the SELECT statement 5 times, I'd like each stored proc to call a single stored proc that executes the SELECT statement and returns the resultset to the calling stored proc

The SELECT statement in question retrieves a single row from a table containing 10 columns.

Is there a way for a stored proc to call another stored proc and gain access to the resultset of the called stored proc?

I know about stored proc return values and about output parameters, but I think I am looking for something different.

Thanks

View 14 Replies View Related

Calling T SQL Stored Proc From CLR Stored Proc

Aug 30, 2007

I would like to know if the following is possible/permissible:

myCLRstoredproc (or some C# stored proc)
{
//call some T SQL stored procedure spSQL and get the result set here to work with

INSERT INTO #tmpCLR EXECUTE spSQL
}

spSQL
(

INSERT INTO #tmpABC EXECUTE spSQL2
)


spSQL2
(
// some other t-sql stored proc
)


Can we do that? I know that doing this in SQL server would throw (nested EXECUTE not allowed). I dont want to go re-writing the spSQL in C# again, I just want to get whatever spSQL returns and then work with the result set to do row-level computations, thereby avoiding to use cursors in spSQL.

View 2 Replies View Related

Good Book About Stored Procedure

Mar 5, 2008

Hi:
Can you please recommend 1-2 good books about "stored procedure", I need a book which starts from basic and goes to developed level.
Thanks.
Jt

View 4 Replies View Related

Problems Running A Good Stored Procedure As A Job

Dec 13, 1999

I wrote a Stored Procedure I wish to run as a job. It inserts data to a linked server. The stored procedure runs fine from the sql query analyzer but fails as a job. There are no permissions assigned to this stored procedure as I beleive it runs under the context of sa which has default access granted.

Can someone give me some insite why this stored procedure won't run as a scheduled job?

ALTER PROCEDURE tsul_insertintolinkedserver
AS
DECLARE @srvname varChar(20)
SELECT @srvname = @@servername
insert into THOMAS.tsnet.dbo.usagelog
select id, tsgroup, account, error, failedpin, type, servername, ipbrowser, cid, logintime, expand , msgspresent, msgslistened, @srvname
from usagelog
where id >
( select max(id) from THOMAS.tsnet.dbo.usagelog
where hostserver = @srvname
)

Thanks in advance-

View 7 Replies View Related

A Good Insert Record If Non Existant Stored Procedure

May 26, 2004

Can anyone spare me a good SP that ....

checks if the record exists - and if so return the identity.

and if the record does not exist

inserts it and returns the identity.

Mine keep flipping up :) so I rather look at someone else and use theirs.

Thanks in advance.

View 3 Replies View Related

Stored Procs And Source Safe Good Idea?

Sep 25, 2000

Hi,
Any pros and cons of putting sprocs into Source Safe?

Thanks,
Judith

View 2 Replies View Related

Stored Procedure - SELECT INSERT Statement - Good Practice?

Jan 9, 2004

I would like to have a stored procedure executed once a week via a DTS package. The data I would like inserted into Table_2, which is the table where the DTS is being executed on, comes from a weekly dump from Oracle into a Table_1 via another DTS package.

I would like to only import data since the last import so I was thinking of my logic to be like this:

INSERT INTO Table_2
(Field1, Field2, ... , FieldN)
VALUES (SELECT Field1, Field2, ... , FieldN FROM Table_1 WHERE ThisDate > MAX(Table_2.ThatDate))

Does this make sense? Or do you all suggest a different mannger of accomplishing this?

View 8 Replies View Related

Building Query Strings Within Stored Procs - Good Or Evil?

Feb 4, 2008

I ran across this technique being used in an application the other day. It seems not a good idea to me. What do you think?

1. The proc builds a basic query, nothing real fancy, into a string variable called @SQL defined as varchar 2000. Depending on the result desired, the group by clause can be one of three different sort orders.

2. The string is executed via EXEC @SQL.

It seems to me that the whole process can eliminate the EXEC and just use some other construct. All the parameters are passed in via the initial call to the stored proc. It also seems that every time this is executed it will result in a new query compile and cache useage, no matter what. Wasteful? Should I take the developers aside and knock heads? I think the app was coded by some folks who were rookies then but may be willing to crack open their code. Or, am I the one that is a rookie?

Thanks for your inputs.

View 11 Replies View Related

Execute Stored Procedure Y Asynchronously From Stored Proc X Using SQL Server 2000

Oct 14, 2007

I am calling a stored procedure (say X) and from that stored procedure (i mean X) i want to call another stored procedure (say Y)asynchoronoulsy. Once stored procedure X is completed then i want to return execution to main program. In background, Stored procedure Y will contiue his work. Please let me know how to do that using SQL Server 2000 and ASP.NET 2.

View 3 Replies View Related

How Can I Call One Or More Stored Procedures Into Perticular One Stored Proc ?

Apr 23, 2008

Hello friends......How are you ? I want to ask you all that how can I do the following ?
I want to now that how many ways are there to do this ?



How can I call one or more stored procedures into perticular one Stored Proc ? in MS SQL Server 2000/05.

View 1 Replies View Related

Calling A Stored Procedure From Within A Stored Proc

Dec 18, 2007

Hi Peeps
I have a SP that returns xml
I have writen another stored proc in which I want to do something like this:Select FieldOne, FieldTwo, ( exec sp_that_returns_xml ( @a, @b) ), FieldThree from TableName
But it seems that I cant call the proc from within a select.
I have also tried
declare @v xml
set @v = exec sp_that_returns_xml ( @a, @b)
But this again doesn't work
I have tried changing the statements syntax i.e. brackets and no brackets etc...,
The only way Ive got it to work is to create a temp table, insert the result from the xml proc into it and then set @v as a select from the temp table -
Which to be frank is god awful way to do it.
 Any and all help appreciated.
Kal

View 3 Replies View Related

Using Views Within Stored Procedures

Jul 22, 2007

Good evening:Can anyone give me the low-down on using view from within my stored procedures?  I've got some rather complex views that join multiple tables resulting in a staggering SQL query.  I then use stored procedures to accept input parameters to determine order by and direction clauses.  This results in some rather large "IF ELSE IF ELSE IF..." statements in my SP.  Put a complicated SQL query together with lots of IF THEN and it becomes difficult to keep stuff straight in the SP.  Therefore, using the view to keep my SQL in one place is an ideal solution. However, and here's the question, does it have a negative impact on speed and/or scalability.  We plan to use these SP's within an ASP.NET website that may get a very large amount of traffic. Any advice/help you can give me would be really appreciated. Thanks!
- Future Daddy
 

View 2 Replies View Related

Getting At Views And Stored Procedures

Feb 15, 2001

I have been having troubling getting at views and stored proceduers with ADO objects while developing in VB.

I can get a list of the views and stored procedures, but I don't know how to actually get the text values of them... i would like the text so that I can parse/compare them agianst one another...

Any thoughts or help on this?

I would really appreciate the help!

Matt

View 2 Replies View Related

Views And Stored Procs.

Aug 31, 2004

Is there any performance loss by setting up a view and creating a stored procedure to return a recordset from a view versus setting up the stored procedure to return the recordset from the tables directly?

What way should I do this?

Mike B

View 2 Replies View Related

Views In Stored Procedures?

Feb 16, 2007

Hello,

This maybe a simple question, I'm using reporting services to make a report, question is can I write a stored procedure that queries from a join of two views instead of two tables?

I'm having trouble getting my table data into the reportable state I want it, and I think organising into views might be easier.

Thanks for any help.

View 3 Replies View Related

Under Which Filegroup Are Stored Proc. Stored?

Aug 23, 2007

When you create a Stored procedure, is it automatically stored under the default Filegoup?

How can I see under which Filegroup my Stored Procedures and Triggers are stored?

View 2 Replies View Related

Views Inside Stored Procedures.

Apr 18, 2007

Hi everybody,I am trying to alter a view inside a Stored Procedure and sql server is not allowing me to do so.Can we not have an alter view inside a Stored Procedure?Here is the code: CREATE PROCEDURE dbo.[UPDATE_VIEW_LINEITEMALLOTMENT]     -- Add the parameters for the stored procedure here@MAINID int,@BE VARCHAR(8)ASBEGIN    -- SET NOCOUNT ON added to prevent extra result sets from    -- interfering with SELECT statements.    --SET NOCOUNT ON;        ALTER VIEW [Budget_Management_System].[dbo].[LineItem_OCAFund]        AS        SELECT     TOP (100) PERCENT SUM(dbo.ALL_OCAFUND.AMOUNT) AS Expr2, dbo.APP_LINEITEM.LINENUM, dbo.APP_LINEITEM.PC,                               dbo.APP_LINEITEM.CATEGORY, dbo.APP_LINEITEM.ROWID, dbo.APP_LINEITEM.MAINID        FROM         dbo.APP_LINEITEM INNER JOIN                              dbo.ALL_ORG ON dbo.APP_LINEITEM.ROWID = dbo.ALL_ORG.LINEITEMID INNER JOIN                              dbo.ALL_OCAFUND ON dbo.ALL_ORG.ROWID = dbo.ALL_OCAFUND.ORGID INNER JOIN                              dbo.APP_AMENDMENT ON dbo.ALL_ORG.AMENDMENTID = dbo.APP_AMENDMENT.ROWID AND                               dbo.ALL_OCAFUND.AMENDMENTID = dbo.APP_AMENDMENT.ROWID        GROUP BY dbo.APP_LINEITEM.LINEORDER, dbo.APP_LINEITEM.BE, dbo.APP_LINEITEM.MAINID, dbo.APP_LINEITEM.LINENUM, dbo.APP_LINEITEM.PC,                               dbo.APP_LINEITEM.CATEGORY, dbo.APP_LINEITEM.ROWID, dbo.APP_AMENDMENT.AMENDMENTORDER        HAVING      (dbo.APP_LINEITEM.BE = @BE) AND (dbo.APP_LINEITEM.MAINID = @MAINID) AND (dbo.APP_AMENDMENT.AMENDMENTORDER = 1)        ORDER BY dbo.APP_LINEITEM.LINEORDER   ENDthanks a lot,Murthy here 

View 7 Replies View Related

Accessing Views From Stored Procedures

Sep 7, 2007

Hi,I was just wondering if it's possible to access views from stored procedures? I know it doesn't make much sense, but would it be possible? If so, can you also give me some code example?Thanks. 

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved