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, if
so, drop, then create the proc. I just wanted to know why that's a best
practice. I am trying to put that theory in place at my work, but they are
asking for a good reason to do this before actually implementing. All I
could think of was that so when you're creating a proc you won't get an
error if the procedure already exists, but doesn't it also have to do with
Compilation and perhaps Execution. Does anyone have a good argument for
doing stored procs this way? All feedback is appreciated.
TIA,
~CK
View 3 Replies
ADVERTISEMENT
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
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
Mar 23, 2006
I was wondering if it is possible to create a stored procedure to create databases. The only parameter would need to be the name of the database. Do I have to use a bunch of EXEC statements, or is there a better way?
I've created basic stored procs before, but never one for something like this.
Thanks.
View 3 Replies
View Related
Dec 7, 2004
Hello SQL Server programming gurus:
I am trying to create a trigger that fires after a user logon and logoff and does the following:
creates a new user
deletes data from old temp table
Then I need to create a stored procedure that executes dynamically to
drop old users
remove the old user account access
We are running SQL Server 2000.
Since I am new to T-SQL programming could anyone help point me in the right direction? Can I write dynamic SQL in a trigger to do these things?
View 1 Replies
View Related
Apr 5, 2006
My simple CLR Stored procedure is as below:
[Microsoft.SqlServer.Server.SqlProcedure]
public static int MyParallelStoredProc(string name1, string name2)
{
Thread t = null;
Worker wth = null;
int parallel = 2;
Object[] obj = new object [parallel];
SqlPipe p;
p = SqlContext.Pipe;
for (int i = 0; i < parallel; i++)
{
if (i == 0)
wth = new Worker(name1);
else
wth = new Worker(name2);
t = new Thread(new System.Threading.ThreadStart(wth.WorkerProc));
t.Name = "Thread -" + i.ToString() + ":";
t.Start();
p.Send(t.Name + ":Started");
obj[ i] = t;
}
for (int i = 0; i < parallel; i++)
{
t = (System.Threading.Thread)obj[ i];
t.Join();
p.Send(t.Name + ":Finished");
}
return 0;
}
The worker class implementing Thread Proc:
public class Worker
{
private string Name;
public Worker(string name)
{
SqlPipe p;
p = SqlContext.Pipe;
Name = name;
p.Send("In Constructor:" + Name);
}
public void WorkerProc()
{
SqlPipe p;
p = SqlContext.Pipe;
for (int i = 0; i < 10; i++)
p.Send(i.ToString()+":"+Name);
}
}
The assembly is registered with UNSAFE permission set.
CREATE ASSEMBLY
ThreadTest
FROM
'C:\ThreadTestinDebugThreadTest.dll'
WITH
permission_set = unsafe;
GO
CREATE PROC ParallelStoredProc
@Name1 NVARCHAR(1024),
@Name2 NVARCHAR(1024)
AS
EXTERNAL NAME ThreadTest.[MyTest.ThreadTest].MyParallelStoredProc
When I invoke the the stored procedure from T-SQL script as below,
EXEC ParallelStoredProc @Name1, @Name2
the thread class constructor gets called; but the 'WorkerProc' does not execute ?
Whether an UNSAFE assembly is allowed to spawn threads
inside SQL Server ?
View 8 Replies
View Related
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
Aug 21, 2007
Hello,
i need to create temporary table inside SP.
i having one string variable @strQuery which contain dynamic query inside SP.
i am executing that trhough execute sp_executesql @strQuery once query build.
now instead of select query , i want to creat hash table.
so i wrote :
set @strQuery = "Select * into #tmp_tbl from table_name..."
when i tried to execute it through
execute sp_executesql @strQuery , its giving error 'Invalid object name '#tmp_tbl'
If i removed Hash then it works fine. even for double Hash also its work fine.
but i want hash table only as i want that table local to that user.
Even direct execution of select statement without @strQuery works fine. but i want to execute @strQuery through execute sp_executesql @strQuery only as query is dynamic .
please guide me how to do this?
its very urgent for me.
thanks in advance.
View 4 Replies
View Related
Aug 25, 2015
I have a Stored proc which on execution, will generate data in the view .
My requirement is using SSIS, how can I create a Flat file pointing to this view ?
View 2 Replies
View Related
Jun 15, 2008
I try to drop a proc:
IF OBJECT_ID('dbo.Notify_Insert') IS NOT NULL
DROP PROC dbo.Notify_Insert
GO
CREATE PROC dbo.Notify_Insert (
@NotifyID UNIQUEIDENTIFIER,
@NotifyTypeID SMALLINT,
@Reporter VARCHAR(200),
@NotifyTime DATETIME
)
AS
SET NOCOUNT ON
DECLARE @Error INT
DECLARE @ErrorMsg VARCHAR(200)
GO
and get Error:
Msg 2812, Level 16, State 62, Procedure Notify_DBError_Insert, Line 20
Could not find stored procedure 'dbo.Notify_Insert'.
The statement has been terminated.
any idea ?
Noam Graizer
View 4 Replies
View Related
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
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
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
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
Jul 27, 2006
Every day we are restoring prod DB in Development env. I need to save before restore users stored proc,
restore DB and after create SP from file.
Thanks.
View 3 Replies
View Related
Aug 4, 2004
Hi All,
I'm trying to create a proc for granting permission for developer, but I tried many times, still couldn't get successful, someone can help me? The original statement is:
Create PROC dbo.GrantPermission
@user1 varchar(50)
as
Grant create table to @user1
go
Grant create view to @user1
go
Grant create Procedure to @user1
Go
Thanks Guys.
View 14 Replies
View Related
Mar 2, 2004
Gurus help me:
Here's the scenario...
Have a SP in the Master DB that creates a NEW, empty DB using a name I give it on the fly.
I need to Create a SP in that NEW DB.
Everything will be called from a DTS Package.
How to do this?
RobbieD
View 14 Replies
View Related
Mar 22, 2006
samir khatri writes "hello sir,
i m new in the world of database so please help me to create a perticular store proc
i want to get data from 3 tables and 2 field of a table is match with the same field of another table and it cant work
i write that code so u can understand easily but it dont work so please modify that and make it workable
select a.a_dis_id,b.name as fromname,b.name as toname,a.a_dis_km,c.a_all_name,c.a_all_rate from
a_distance a,levels b,a_allowance c where
a.a_dis_from=b.cid and a.a_dis_to=b.cid and c.a_all_id=a.a_all_id
Thank You
Waiting for yur reply....."
View 3 Replies
View Related
Apr 8, 2004
Is it possible to retrieve the resultset of a stored procedure from another procedure in sql server 2000.
Basically I am calling proc2 from the inside of proc1.
proc2 returns 2 resultsets. I want to process these two resultsets
from within proc1.
If its possible , please provide sample code.
thanks in advance,
Alok.
View 1 Replies
View Related
Feb 5, 2015
Without giving dbowner how can we grant permission to user to alter/create procs?
View 3 Replies
View Related
Feb 16, 2005
Can someone give me a clue on this. I'm trying to insert values based off of values in another table.
I'm comparing wether two id's (non keys in the db) are the same in two fields (that is the where statement. Based on that I'm inserting into the Results table in the PledgeLastYr collumn a 'Y' (thats what I want to do -- to indicate that they have pledged over the last year).
Two questions
1. As this is set up right now I'm getting NULL values inserted into the PledgeLastYr collumn. I'm sure this is a stupid syntax problem that i'm overlooking but if someone can give me a hint that would be great.
2. How would I go about writing an If / Else statement in T-SQL so that I can have the Insert statement for both the Yes they have pledged and No they have not pledged all in one stored proc. I'm not to familar with the syntax of writing conditional statements within T-SQL as of yet, and if someone can give me some hints on how to do that it would be greatly appriciated.
Thanks in advance, bellow is the code that I have so far:
RB
Select Results.custID, Results.PledgeLastYr
From Results, PledgeInLastYear
Where Results.custID = PledgeInLastYear.constIDPledgeInLastYear
Insert Into Results(PledgeLastYr)
Values ('Y')
View 1 Replies
View Related
Jul 19, 2007
Im trying to perform an update with a stored procedure thats all working but
an exception is thrown ....violation of primary key contraint....cannot insert duplicate pri key
I understand whats going on but how do you update some ones details if its protected this way.
?
View 3 Replies
View Related
Feb 22, 2008
I have a stored procedure , where i want to return identity column after insert but before insert i want to check if the record exist then select its identity value to return , after select statement it is retutrning null CREATE PROCEDURE SP_Attendance1 (@DIVISIONID int,@EMPLOYEEID int,@CALLDATE datetime,@RECEIVEDDATE datetime,@DOC datetime,@SYSTEMNAME VARCHAR(20),@DELETED int,@attendanceID int output) AS---DECLARE @ID intIF EXISTS (SELECT ID FROM TBLATTENDANCE WHERE EMPLOYEEID = @EMPLOYEEID AND YEAR ( CALLDATE ) = YEAR ( @CALLDATE)AND MONTH (CALLDATE) = MONTH ( @CALLDATE) AND DAY (CALLDATE) = DAY ( @CALLDATE) )BEGIN SET @attendanceID = SCOPE_IDENTITY()END ELSE BEGIN INSERT INTO TBLATTENDANCE (DIVISIONID ,EMPLOYEEID ,CALLDATE , RECEIVEDDATE ,DOC,SYSTEMNAME ,DELETED )VALUES (@DIVISIONID ,@EMPLOYEEID ,@CALLDATE , @RECEIVEDDATE ,@DOC,@SYSTEMNAME ,@DELETED ) ;SELECT DIVISIONID, EMPLOYEEID, CALLDATE, RECEIVEDDATE, DOC, SYSTEMNAME, DELETED,ID FROM TBLATTENDANCE WHERE (ID = SCOPE_IDENTITY())SELECT @attendanceID = SCOPE_IDENTITY()ENDGO Kindly help with this
View 5 Replies
View Related
Jan 15, 2004
Hi,
I am trying to create a stored proc, that delivers a recordset, per the user requirements BUT,
I want to create a Geneirc search Proc that can handle a few criteria
I was wondering if it is possible to create a VB like Select case
depending on Information supplied to the stored proc
i.e
@Loc_Thing
@Loc_OtherThing
SELECT FirstName,LastName,CIty,Job,,Company,Webpage FROM RECORDSET WHERE
Select case @Loc_Thing
Case "Mickey"
LastName = @Loc_OtherThing
Case "Walt"
Company = @Loc_OtherThing
...... etc
is it possible to create a strored proc like this?
I have found a Select case in SQL, but it doesn't work I would like it?
Any Idea's?
View 1 Replies
View Related
Nov 29, 2004
Hello,
So I created my first SP today which returned data to populate a datagrid. Worked to perfection. Now I'm trying to do a simple login and I'm having a hard time getting it together. I want the user to enter in a username and pass then if user exists, to return their userid and update their last login date. But I can't get it. Any help would be awesome.
Here's my SP...
CREATE PROCEDURE [dbo].[userLogin] @username varchar(50), @pass varchar(50) AS
declare @x int
declare @userid int
if exists (SELECT userid FROM users WHERE username = @username AND password = @pass)
set @x = 1
else
set @x = 0
if @x = 1
UPDATE users SET lastlogin = getdate() WHERE userid = (SELECT userid AS name FROM users WHERE username = @username AND password = @pass)
else
return '0'
if @x = 1
SET @userid = (SELECT userid FROM users WHERE username = @username AND password = @pass)
return @userid
GO
Any constructive criticism on my SP is welcome. Also, should I be using Print or Return if I want to send back a value to my VB code?
And my VB:
Dim user As String = txtUsername.Text
Dim pass As String = txtPassword.Text
Dim objDataSet As DataSet
Dim objAdapter As SqlDataAdapter
Try
Dim cmd As New SqlCommand
'Enter Param's here
Dim myParam1 As SqlParameter = cmd.Parameters.Add("@username", SqlDbType.VarChar)
Dim myParam2 As SqlParameter = cmd.Parameters.Add("@pass", SqlDbType.VarChar)
myParam1.Value = user
myParam2.Value = pass
objAdapter = New SqlDataAdapter
objAdapter.SelectCommand = cmd
objAdapter.SelectCommand.Connection = SqlConn
objAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
objAdapter.SelectCommand.CommandText = "userLogin"
SqlConn.Open()
Dim str As String = cmd.Parameters("@userid").Value()
cmd.ExecuteNonQuery()
If str = "0" Then
'Error Login Page
Response.Redirect("login_err.aspx")
Else
Session("userid") = str
Response.Redirect("home.aspx")
End If
SqlConn.Close()
Catch ex As SqlException
SqlConn.Close()
End Try
View 4 Replies
View Related
Feb 13, 2006
I have 2 tables, lets say: Table1 and Table2.
Table1 has an ID field that is unique (PK).
Table2 has the same ID field and a date field which are both
unique (PK, FK)
I need to write a stored procedure that will query the ID
field from table1 like
Select distinct(id) from Table1
Would return:
ID
1
2
3
4
5
Now on the first of every month I want a job to run that
would create a new record for EACH ID from the above query. The new record would be created in Table2
with the ID and a date (that I will determine), resulting in:
ID DATE
1 01/01/06
2 01/01/06
3 01/01/06
4 01/01/06
5 01/01/06
The following month, after running it again, the table would
look like:
ID DATE
1 01/01/06
1 02/01/06
2 01/01/06
2 02/01/06
3 01/01/06
3 02/01/06
4 01/01/06
4 02/01/06
5 01/01/06
5 02/01/06
I have no idea how to “loop� through this record set for
each record in Table1 and in turn insert into Table2.
View 2 Replies
View Related
Mar 30, 2006
I have a current stored proc that creates records based on
certain criteria. One of the fields I
have is a SmallDateTime field. To
populate this from my stored proc, I have this code (for this one field).
SELECT @myLeaveDate = CAST(STR(MONTH(getdate()))+'/'+STR(01)+'/'+STR(YEAR(getdate())) AS DateTime)
This always creates a record for the 1st of the
current month. This works fine as is. After it runs I can look at the table and it
creates dates that look like the following: “2/1/2006� -Notice it doesn’t have
any minutes, seconds, etc.
Now what I need is to do something similar in another field
which is also SmallDateTime, BUT I want the date to be for the 10th day
of the following month.
I got this working using dateadd, but it also appends the minutes, seconds,
etc.
View 1 Replies
View Related
May 9, 2001
Can I call a sp from within a sp ?
Is this a fairly normal practice ?
Thanks,
Ivan
View 2 Replies
View Related
Sep 15, 1999
Can someone help us with this stored proc.
We need the maxccid -1 to be passed as a value.
Here is the proc.
CREATE PROCEDURE NewBillingInfo
@int_acct_id char (10)
@cc_nickname varchar (20),
@cc_zip varchar (20),
@cc_name varchar (100),
@cc_num varchar (20),
@cc_typ varchar (20),
@cc_month char (2),
@cc_year char (4)
as
set nocount off
declare @maxaddrid int
declare @maxccid smallint
/* BEGIN ENCRYPT DATA*/
exec encrypt @cc_zip output, @cc_zip
exec encrypt @cc_name OUTPUT, @cc_name
exec encrypt @cc_num OUTPUT , @cc_num
exec encrypt @cc_typ OUTPUT, @cc_type
exec encrypt @cc_month OUTPUT, @cc_month
exec encrypt @cc_year OUTPUT, @cc_year
BEGIN TRAN
/* get max credit card id for customer and add 1 */
SELECT @maxccid = Max(int_cc_id) from CusCredit where int_acct_id = @int_acct_id
if @maxcced is null
SELECT @maxccid = -1
SELECT @maxccid = @maxccid + 1
INSERT INTO CusCredit
(int_acct_id, int_cc_id, cc_name, cc_num,
cc_typ, cc_month, cc_year, cc_zip, cc_nickname)
VALUES
(@int_acct_id, @maxccid, @cc_name, @cc_num,
@cc_type, @cc_month, @cc_year, @cc_zip, @cc_nickname)
if @@ROWCOUNT < 1
BEGIN
ROLLBACK TRAN
RETURN 103
end
COMMIT TRAN
RETURN
GO
If someone could take a minute and look at this I would be so grateful.
Thanks Dianne Watson
View 1 Replies
View Related
Nov 29, 2000
I made a strored proc and I receive my like condition in parameter. The like condition must be in '' like (... like 'a%'). I'm sure that it's just a question of apostrophe.
for example:
declare @Command varchar(8000)
declare @Compagnie varchar(100)
select @Compagnie = 'Tonna%'
select @Command = 'SELECT distinct [Site Status].DISTRIBUTION, [Site Status].CC FROM [Site Status] WHERE [Site Status].CC like ' +@Compagnie
execute (@Command)
how can i write that @Compagnie is in apostrophe
thanks
View 1 Replies
View Related
Feb 16, 2004
Hi,
Anybody has Document for Stored procedure coding standard for best performance.
I know that I can able get in BOL and sql-server-performance.com just wanted know if anybody had info other than this.
Thanks,
Ravi
View 1 Replies
View Related
Aug 28, 2002
I want to generate getdate without the timestamp, only the date. Any ideas. Datepart will not convert to varchar as needed within this proc.
View 2 Replies
View Related
Jun 20, 2001
One of the columns I am inserting into may or may not contain sensitive data. If the "type" parameter supplied with the proc. execute statement is of a specific value I need to utilize an encryption function (and a data type conversion) on the following column which is the actual value parameter. If the type does not meet the specific criteria the encryption/conversion for the value parameter.
Any syntax assist would be greatly apprciated.
View 2 Replies
View Related