Is it possible to modify the "alter procedure" template in SSMS? - sql-server

I know how to modify "CREATE PROC" templates in SSMS, and I wonder if I can modify the "ALTER PROC" template, which shows when I right-click on an existing stored procedure and click "Modify". When I click "Modify", a script "ALTER PROC ..." will be generated, I hope I can modify this so it can generate
IF EXISTS ()... DROP PROC ... CREATE PROC ...
instead of
ALTER PROC
Alternatively, if I can create a new template to achieve the same goal, that would be good too.
Thanks.

I don't think there is, but you can get pretty close to faking it. Create a snippet (in my version of SSMS, there's a Code Snippet Manager in the Tools menu) for the "if exists... drop" part. Now, script your procedure, insert your snippet at the top and you should be good to go.
I would be remiss if I didn't mention that dropping a procedure drops any explicit permissions that have been granted or denied on it. If you're doing this so that you get an idempotent script, I've adopted this idiom to avoid that problem:
if object_id('someSchema.yourProc') is not null
set noexec on;
go
create procedure someSchema.yourProc
as
print 'not yet implemented'
go
set noexec off;
go
alter procedure someSchema.yourProc as
begin
-- your actual proc
end

Yes, In modify option, you can directly modify or alter prc as
ALTER PROCEDURE [dbo].[sp_name]
#paramater INT , .... other
AS
BEGIN
.... statement
END
What the good thing in below option, is when you give to some one or deploy on server. Its good to give below type of statement.
Which first verefiy that Procedure exist or not, if exist then it first drop and then create.
IF EXISTS ()... DROP PROC ... CREATE PROC ...
Modify option means right-click and modify which directly give, alter option which is good for development purpose. You know while development like alter table or change sp parameter name. that also include when you give to someone with current sp.
While to give some one , good to drop and create with exist option, so third party easily execute without error.

Related

What is "dummy" in CREATE PROCEDURE statement

I'm doing investigation of code repo and find one thing that make me confused. SQL Server stored procedures are contained in a repo as a set of queries with following structure:
IF OBJECT_ID(N'[dbo].[sp_ProcTitle]', N'P') IS NULL
BEGIN
EXEC dbo.sp_executeSQL N'CREATE PROCEDURE [dbo].[sp_ProcTitle] AS dummy:;';
END
ALTER PROCEDURE dbo.sp_ProcTitle
#ParamOne int,
#ParamTwo date,
#ParamThree int
AS
SET NOCOUNT ON
-- some procedure body
END
Never before I saw AS dummy:; and now I'm a little confused, I can't find any good explanation what is it and how it works. Could anybody tell me what does it mean this statement? How it works? What is the reason to have it? Any thought would be good to hear. Or, please, advise me some link where I can find good explanation.
This is simply a label, such that could be used in a GOTO statement.
The word "dummy" is unimportant. It's simply trying to create the stored procedure if it doesn't exist, with a minimal amount of text. The content is then filled in with the ALTER.
Conceivably, the dummy text could later be searched for to see if any procedures were created and didn't have their content filled in, to check against failed deployments, etc.
Why do this? Well, it preserve the creation time of the stored procedure in metadata (which can be useful in administration or tracking down problems), and is compatible with versions of SQL Server that lack the CREATE OR ALTER... support.
This might make a little more sense if we add a little formatting to the CREATE:
CREATE PROCEDURE [dbo].[sp_ProcTitle]
AS
dummy:
This is, effectively, an empty procedure with a label called dummy. The user appears to be using this to ensure that the procedure exists first, and the ALTERing it. In older versions of SQL Server, such methods were needed because it didn't support CREATE OR ALTER syntax. As such, if you tried to ALTER a procedure that didn't exist the statement failed, and likewise if you try to CREATE a procedure that already exists it fails.
If you are on a recent version of SQL Server, I'd suggest changing to CREATE OR ALTER and getting rid of the call to sys.sp_executesql.

SQL SERVER 2008 TRIGGER ON CREATE TABLE

Is there a way to run some function like a trigger when a table is created in the database in SQL SERVER 2008?
Yes, it's called a DDL trigger. The documentation for CREATE TRIGGER has a sample for DROP_SYNONYM (a very questionable choice for an example) but you'll want the CREATE_TABLE event instead. A better starting point in understanding how they work is probably here:
http://msdn.microsoft.com/en-us/library/ms190989.aspx
If you have more specific details, e.g. what exactly do you want to pass to this function (I assume you mean procedure), or what does the procedure do, we can provide more useful and specific help.
Yes a DDL Trigger. For example, here is some code I written to prevent some tables from being modified:
PRINT N'Create DDL trigger to prevent changes to various tables'
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER NoEditCertainTables ON DATABASE
FOR DROP_TABLE, ALTER_TABLE, CREATE_TABLE
AS
SET CONCAT_NULL_YIELDS_NULL ON
DECLARE #AffectedTable varchar(255)
SELECT #AffectedTable = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(100)')
--This is the name of the table(s) you dont want messed with
IF (#AffectedTable IN ('Table1','Table2','Table3'))
BEGIN
ROLLBACK;
END
SET CONCAT_NULL_YIELDS_NULL OFF
GO

Disappearing Stored Procedure

So, not sure what is happening. But I have stored procedure and it keeps disappearing out of my DB in SQL 2k.
I can add it again and then try to execute it from my web app and i get an exception saying the stored procedure cant be found. So then ill go back to management and refresh and its gone again !?!
here is the config for the stored proc:
set ANSI_NULLS OFF
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[USP_Equipment_Delete]
#EquipmentID int
AS
DELETE FROM [dbo].[Equipment]
WHERE
[EquipmentID] = #EquipmentID
None of my other stored procedure disappear. This is the only one. I have easily 100 in there. They all use the same SQLHelper class. This one just keeps disappearing!!!??!!
Any help or suggestions are appreciated!
Thanks so much!
You were creating this or another stored proc and at the end of your code, maybe after a comment, where you did not see it you have a drop of this proc.
Take a look at your db using:
select syo.name
from syscomments syc
join sysobjects syo on
syo.id = syc.id
where syc.[text] like '%DROP PROC%'
I had the same problem and I just fixed it:
In the script file it was missing the "GO" statement between the end of the stored procedure and the beginning of the next "IF EXIST THEN DROP" statement.
So what happened was that the drop statement was getting appended to the end of whatever stored procedure was above it in the script. So when the software ran the stored procedure it would drop whatever stored procedure was below it in the script.
It seems so obvious to us now but didn't make any sense at the time. We found it running the SQL profiler against a customer's database that was having the problem in the field.
Are you using the correct database?
Try
using [database name]
prior to executing your stored procedure, just to make sure.
Do you have a CREATE PROCEDURE anywhere? You can't ALTER a procedure if it doesn't exist.
Perhaps the code to access the stored procedure is using a different context other than dbo. Make sure to add dbo.USP_Equipment_Delete to the code using it.
I was facing the problem that all Stored Procedures with a create statement disappeared from the database after execution.
The Solution was: The database user should have the rights to drop,create and alter on the database in which the "Stored Procedures" are going to be created.
Perhaps there's a job thats restoring an old backup periodically?
Check if the "Initial Catalog" in your connection string is set to the correct database.
Put the database in single user mode (and make sure you're the single user) and check if the procedure still disappears every hour?
If it's there, then this query must return a record:
SELECT * FROM sysobjects
WHERE id = OBJECT_ID('USP_Equipment_Delete')
AND OBJECTPROPERTY(id, N'IsProcedure') = 1

Altering a trigger in Sql Server 2005

I need to alter a trigger in sql server 2005 and I want to do it using a table adapter and a sql statement, not a stored proc. I know I could run this in the query browser and execute it but I need to deploy it across several databases and use a table adapter in the update. Is this possible?
Doing Add Query -> Update -> pasting the below code -> Query Builder to see if it parses
print("USE [DataBaseName]
GO
/****** Object: Trigger [dbo].[UpdateCurrentAddress] Script Date: 10/30/2008 14:47:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[UpdateCurrentAddress] ON [dbo].[PreviousAddresses]
FOR INSERT, UPDATE, DELETE
AS
-- Check to see if there was an insert/update or a deletion.
IF (SELECT COUNT(*) FROM inserted) >= 1
BEGIN
IF (SELECT CountryID FROM inserted) <> 181
...moar...");
error...
The USE [DataBaseName] SQL construct or statement is not supported.
and if i remove the top part and start at just ALTER TRIGGER
The ALTER TRIGGER SQL construct or statement is not supported.
I'm still fairly new to this and would not be surprised that either I'm either going about this the wrong way and/or it's impossible to do without a stored proc.
EDIT: Yeah I'm doing this in C#.
thanks. I can do it that way starting at ALTER TRIGGER, this will get the job done.
The TableAdapter is expecting a resultset, not an actual query. To do this successfully you will need to use the SqlCommand object to actually peform your update.
If you have not used one before it is quite simple, first you declare your connection, then you create your command using the connection. Once the command is created set the commandtext equal to your script, and then you can call the ExecuteNonQuery() method to run the script after opening the connection. If you say what language you are using, I can try to provide an example.
Edit
Here is a C# example, quick and dirty but it gets the point across. NOTE, done from memory, but should be correct.
using(SqlConnection oConnection = new SqlConnection("Yourconnectionhere"))
using(SqlCommand oCommand = new SqlCommand(oConnection))
{
//Configure the command object
oCommand.CommandText = "Your script here";
//Open connectin and run script
oConnection.Open();
oCommand.ExecuteNonQuery();
oConnection.Close();
}

How do I conditionally create a stored procedure in SQL Server?

As part of my integration strategy, I have a few SQL scripts that run in order to update the database. The first thing all of these scripts do is check to see if they need to run, e.g.:
if #version <> #expects
begin
declare #error varchar(100);
set #error = 'Invalid version. Your version is ' + convert(varchar, #version) + '. This script expects version ' + convert(varchar, #expects) + '.';
raiserror(#error, 10, 1);
end
else
begin
...sql statements here...
end
Works great! Except if I need to add a stored procedure. The "create proc" command must be the only command in a batch of sql commands. Putting a "create proc" in my IF statement causes this error:
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
Ouch! How do I put the CREATE PROC command in my script, and have it only execute if it needs to?
Here's what I came up with:
Wrap it in an EXEC(), like so:
if #version <> #expects
begin
...snip...
end
else
begin
exec('CREATE PROC MyProc AS SELECT ''Victory!''');
end
Works like a charm!
SET NOEXEC ON is good way to switch off some part of code
IF NOT EXISTS (SELECT * FROM sys.assemblies WHERE name = 'SQL_CLR_Functions')
SET NOEXEC ON
GO
CREATE FUNCTION dbo.CLR_CharList_Split(#list nvarchar(MAX), #delim nchar(1) = N',')
RETURNS TABLE (str nvarchar(4000)) AS EXTERNAL NAME SQL_CLR_Functions.[Granite.SQL.CLR.Functions].CLR_CharList_Split
GO
SET NOEXEC OFF
Found here:
https://codereview.stackexchange.com/questions/10490/conditional-create-must-be-the-only-statement-in-the-batch
P.S. Another way is SET PARSEONLY { ON | OFF }.
But watch out for single quotes within your Stored Procedure - they need to be "escaped" by adding a second one. The first answer has done this, but just in case you missed it. A trap for young players.
Versioning your database is the way to go, but... Why conditionally create stored procedures. For Views, stored procedures, functions, just conditionally drop them and re-create them every time. If you conditionally create, then you will not clean-up databases that have a problem or a hack that got put in 2 years ago by another developer (you or I would never do this) who was sure he would remember to remove the one time emergency update.
Problem with dropping and creating is you lose any security grants that had previously been applied to the object being dropped.
This is an old thread, but Jobo is incorrect: Create Procedure must be the first statement in a batch. Therefore, you can't use Exists to test for existence and then use either Create or Alter. Pity.
It is much better to alter an existing stored proc because of the potential for properties and permissions that have been added AND which will be lost if the stored proc is dropped.
So, test to see if it NOT EXISTS, if it does not then create a dummy proc. Then after that use an alter statement.
IF NOT EXISTS(SELECT * FROM sysobjects WHERE Name = 'YOUR_STORED_PROC_NAME' AND xtype='P')
EXECUTE('CREATE PROC [dbo].[YOUR_STORED_PROC_NAME] as BEGIN select 0 END')
GO
ALTER PROC [dbo].[YOUR_STORED_PROC_NAME]
....
I must admit, I would normally agree with #Peter - I conditionally drop and then unconditionally recreate every time. I've been caught out too many times in the past when trying to second-guess the schema differences between databases, with or without any form of version control.
Having said that, your own suggestion #Josh is pretty cool. Certainly interesting. :-)
My solution is to check if the proc exists, if so then drop it, and then create the proc (same answer as #robsoft but with an example...)
IF EXISTS(SELECT * FROM sysobjects WHERE Name = 'PROC_NAME' AND xtype='P')
BEGIN
DROP PROCEDURE PROC_NAME
END
GO
CREATE PROCEDURE PROC_NAME
#value int
AS
BEGIN
UPDATE SomeTable
SET SomeColumn = 1
WHERE Value = #value
END
GO
use the 'Exists' command in T-SQL to see if the stored proc exists. If it does, use 'Alter', else use 'Create'
IF NOT EXISTS(SELECT * FROM sys.procedures WHERE name = 'pr_MyStoredProc')
BEGIN
CREATE PROCEDURE pr_MyStoredProc AS .....
SET NOCOUNT ON
END
ALTER PROC pr_MyStoredProc
AS
SELECT * FROM tb_MyTable

Resources