SQL procedure vs. script - terminology [closed] - sql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
When one wants to update records in database using Data Manipulation Language, what would be right terminology to use:
UPDATE RECORDS IN TABLE VIA STORED PROCEDURE or
UPDATE RECORDS IN TABLE VIA SCRIPT (or UPDATE SCRIPT)
something else...
NOTE: I know that procedure is not same as script, I wrote question in rush. Real question is if you want to write to your DBA that the defect could be fixed by using (1) or (2) or (3) what would be the right choice. Sorry for not being precise.

If you want to DBA fix some defect, best approach is to write a script file with UPDATE statements, and save it for later use.
If you want that someone else (Job, DBA, App Code) frequently execute same code for updating records in table, then write stored procedure.
Good thing is that you can pass a parameter to stored procedure to affect on range of rows which will be updated.
ONE IMPORTANT THING: Stored procedure are optimized from SQL Optimizer and SQL creates most effective execution plan for it. When you execute it again, SQL find cached execution plan for that procedure and apply it. In this way, you achieve better performance when using stored procedure over script.

A "script" sounds to me like one or more statements that are sent to the database, to perform some action.
A "stored procedure" is that same bunch of statements, but already stored in the database so it can be activated with a simple command.

"Update via stored procedure" is not a synonim to "update via script", so why do you choosing either one or another as term?
Stored procedure - is an object (yes, technically it is some kind of scripit) created and stored in database.
Script - is just a script (sequence of statements). It can be stored in file or just created and executed "on the fly".

If you use just one update statement, then the most appropriate expression is "update records in table via update statement". If you use set of update statements, then it will be a script.
Procedure is an another DBMS object, usually called stored procedure. You can also define a procedure that update data in the database.

Non of the options fit me very well. Sure, if you know an update is being made from a Stored Procedure specifically, that would be fine to use. But an update can be done from many other ways and a Stored procedure can do many other things than just update.
I usually talk about queries and statements, for example:
Update records in a table via an update statement within a Stored Procedure
As for the use of script, I'm personally not that fond of it. There are already many more specific ways to talk about scripts, like Stored procedures, user defined functions, etc. That, for me, is a collection of statements and/or queries.

Related

What's wrong with my stored procedure shown here? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to write a practice stored procedure query.
DELIMITER $$
CREATE PROCEDURE Select_All_Products_Ordered()
BEGIN $$
SELECT *
FROM northwind.Customers
ORDER BY CompanyName;
END $$
DELIMITER ;
It does not recognize the characters' first delimiter, the parentheses after Ordered(), the table name, nor the CompanyName.
Stored Procedure Declaration Syntax
T-SQL (the version of SQL used by SQL Server) does not declare stored procedure parameters with parenthesis. Instead it puts the parameter list between the procedure name and the keyword AS like this:
CREATE PROCEDURE Select_All_Products_Ordered
#myparameter int = 5
AS
-- ...
The procedure does not have to have any parameters, in which case the AS simply follows the procedure name. As such the parenthesis in your code should be replaced with the keyword AS.
DELIMITER
DELIMITER is not used in T-SQL.
This keyword is used in MySql (and possibly other databases) because they are unable to tell if the ; characters in the stored procedure body delimit the end of the the procedure or the end of one statements within the procedure. So to get around this the delimiter is redefined.
T-SQL in contrast will interpret everything from the AS keyword to the end of the batch as part of the stored procedure. As such it does not get confused by the ; characters and does not need to have the delimiter redefined.
The batch will normally run to the end of the file, however, most T-SQL editors will split a script up into batches to send to the server. This is normally done by splitting the script on the word GO at the start of a line. Note it is the editor that does this not SQL Server. Editors like SQL Server Management Studio (SSMS) can have this configured in the settings to a different pattern if you don't like GO. Also libraries like ADO.Net do not do this, so you have to split the script up yourself and send each batch via a separate server call.
BEGIN and END
BEGIN and END are only required if you wish to group a set of statements in to a block. This is useful for WHILE statements for example. As T-SQL treats everything from the AS keyword to the end of the batch as part of the stored procedure, there is no need for them here. That said it won't hurt if you want to leave them.
Missing Schema
Objects such as tables are grouped within SQL Server databases into Schemas. These each have a name, but the default one is dbo. You have used a multipart reference to the Customer table, however though you have given the database and table name you have not given the schema name. To specify the schema you put it between the database and server name like this northwind.dbo.Customers.
It is possible to leave out the schema name and SQL Server will use the default for the database, but in this case you need two dots like this northwind..Customers.
It is also possible to reference a table on a different server if a connection to the other server is registered with the one you are running on. In this case you would use a four part identifier ServerName.DatabaseName.SchemaName.TableName.
You can omit items from the start for the things the server is expected to know. So if you are connected to a particular database you can ommit the server name and database name. Also as mentioned the schema can be omitted and the default for the logged in user will be assumed.
Conclusion
So in order to get the stored procedure to run on SQL Server using a client tool like SQL Server Management Studio you would write it like this (I've included a call to the procedure at the end to show the batch separator, but this isn't required):
CREATE PROCEDURE Select_All_Products_Ordered
AS
SELECT *
FROM northwind.dbo.Customers
ORDER BY CompanyName;
GO
EXEC Select_All_Products_Ordered
GO
More detailed information about T-SQL's stored procedure syntax can be found on Microsoft's Docs site under CREATE PROCEDURE (Transact-SQL).

How to tell if ALTER PROCEDURE worked?

I'm pretty new to SQL and SQL Server. I'm trying to run an ALTER PROCEDURE query from a .sql file called through C# code. Before I move on to making sure my query does what it's supposed to do, I want to verify that my ALTER PROCEDURE query actually altered the procedure, but I don't know how to verify that.
For example, in SQL Server, I can see where the stored procedure I'm trying to edit lives, in:
- database-name
- Programmability/
- Stored Procedures/
- dbo.MyStoredProcedure
If my ALTER TABLE query worked correctly, would I be able to see my procedure code here, or would I check somewhere else? Or am I thinking about this the wrong way?
Generally, we rely on error and exception messages to tell us when something like this has not worked. However, I suppose that it might be possible that the procedure Alter-ed was not the one that was intended (implying bugs in the name/path/call construction, of course).
In that case, you can get the current text of any SQL Module (Procedure, View, Trigger, etc., anything script-baseD) from the sys.sql_modules table:
SELECT definition FROM sys.sql_modules
WHERE object_id=OBJECT_ID('dbo.UserSamples_Insert')
You should note that usually when something like this happens without an error message it is because either:
You are executing in the wrong database (like PROD when you meant to be in DEV or vice-versa), or
You are not using the correct Schema (because you can make and use schemas other than 'dbo').
Wait, you say ALTER PROCEDURE twice, but then the third time you say ALTER TABLE. Which is it? I ask because unlike almost every other SQL object, tables are not script-based and their definition cannot be found in any of the Sql script repositories like sys.sql_modules. I actually use either SMO (from a client) or a tool that #SeanLange wrote years ago for that (from the server itself).

Pre-execute a query when any Stored Procedure is called

Our enterprise's database is 20+ years old, and it's filled with junk, so we're planning to start deleting tables and Stored Procedures. The problem is that we don't exactly know which of those are unused, so we thought on doing a research to spot them.
I tried this answer's solution, but I think the number of queries returned are the ones in the system cache.
I have an idea of how to do it, but I don't know if it's possible:
- Create a system table with 3 columns: Stored Procedure name, number of executions, and date of last call
- The tricky part: everytime a Stored Procedure is executed, perform a query to insert/update that table.
To avoid having to modify ALL our Stored Procedures (those are easily 600+), I thought of adding a Database Trigger, but turns out it's only possible to link them to tables, not Stored Procedures.
My question is, is there any way to pre-execute a query when ANY Stored Procedure is called?
EDIT: Our Database is a SQL Server
I'm aware that I asked this question a while ago, but I'll post what I've found, so anyone who stumbles with it can use it.
When the question was asked, my goal was to retrieve the number of times all Stored Procedures were executed, to try to get rid of the unused ones.
While this is not perfect, as it doesn't show the date of last execution, I found this query, which retrieves all Stored Procedures on all databases, and displays the number of times it's been executed since it's creation:
SELECT
Db_name(st.dbid) [Base de Datos],
Object_schema_name(st.objectid, dbid) [Schema],
Object_name(st.objectid, dbid) [USP],
Max(cp.usecounts) [Total Ejecuciones]
FROM
sys.dm_exec_cached_plans cp
CROSS apply sys.Dm_exec_sql_text(cp.plan_handle) st
WHERE
Db_name(st.dbid) IS NOT NULL
AND cp.objtype = 'proc'
GROUP BY
cp.plan_handle,
Db_name(st.dbid),
Object_schema_name(objectid, st.dbid),
Object_name(objectid, st.dbid)
ORDER BY
Max(cp.usecounts)
I found this script on this webpage (it's on spanish). It also has 2 more useful scripts about similar topics.
I used this script (subsequently improved)
https://chocosmith.wordpress.com/2012/12/07/tsql-recompile-all-views-and-stored-proceedures-and-check-for-error/#more-571
To run through all of your objects and find the ones that are no longer valid.
If you want I will post my enhanced version which fixes a few things.
Then create a new schema (I call mine recycle) and move those invalid objects in there.
Now run it again.
You may end up moving a whole bunch on non functional objects out

Is it possible to limit the permissions on a per procedure basis?

I am writing a sql procedure where almost everything will be dynamic including selecting, grouping, ordering by, and where clauses using IN statements. In terms of code reuse, readability, and maintenance it makes a lot of sense to just pass in an sql query as a string and execute it. I am writing my procedure right now so that all the relevant data is joined and formatted in a static query and then inserted into a table variable. I then want to pass in sql queries to be executed against the table variable.
This opens me up to sql injection in a big way. I could create table value parameters for each of the many parameter types I am passing in but I don't want to do that. What I would really like to be able to do sandbox my procedure in a such a way that, on the procedure level, it is only possible to do these things I want to allow; ie select from certain tables, but not grant permissions or anything funny like that. Can this be done?
Of course it can be done. It's a simple matter of programming. You would keep rules in tables, and write logic in your stored procedure to query the rules tables, and follow the rules.
It will be a monumental job that will basically amount to you writing custom code to do what SQL Server already does for you if you don't use a generic, dynamic stored procedure.
I wouldn't do it, but you don't have to let that stop you.

How to Schedule a trigger? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
We had created a trigger for inserting a set of rows.
I want to schedule this trigger automatically and insert these data into another table. i.e, it has to execute automatically based on the period given.
Kindly suggest the possibilities steps for this.
Here i give you the clear explanation about the operation,
My project to transfer the data from MS SQL database table to MY SQL Database table. This event has to be scheduled. I have to select few fields from MS Sql table and that selected data to be transfer to My Sql table Automatically based on Scheduled.
You could use mysql event scheduler to configure and run your job.
Please have look into
http://dev.mysql.com/doc/refman/5.1/en/events-configuration.html
First, Trigger is one database object and trigger created over the any physical table. this is depends on table action so at every action of table trigger will execute.
we cant schedule trigger to execute on perticluar time.
There is alternative solution is: Enable and Disable trigger using scedule SQL Job.
Script is :
--To Enalble Trigger
ENABLE TRIGGER [Trigger_Name] ON [TableName]
GO
--To Disable Trigger
DISABLE TRIGGER [Trigger_Name] ON [TableName]
GO
If you're using MS SQL, then you can use SQL Server Agent to schedule a job/task to execute whatever you need done.
You can read more about it here http://msdn.microsoft.com/en-us/library/ms191439.aspx
Your best bet maybe to create a stored procedure and then in the scheduled job, simply execute that stored procedure to run.
Alternatively, if you don't have SQL Server Agent (requires full version of MS SQL not SQL Server Express) then you could possibly look into using Windows Scheduled Task to schedule a batch file to run periodically, making a call to the sqlcmd utility http://technet.microsoft.com/en-us/library/ms165702(v=sql.105).aspx which you should be able to setup to execute your stored procedure.
Hope this helps.