Case sensitive variable names in SQL Server? [closed] - sql

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
When I execute this format of SQL command: SP_HELPTEXT Sproc1 .
The result set will display Could not find stored procedure 'SP_HELPTEXT'. But if i will replace the SQL command to lower case like sp_helptext Sproc1 , it definitely displays the content of Sproc1.
Im using the Sproc1 in my program and when the program executes Sproc1 it will return a message:
Must declare the variable '#Variable1'.
Although I've already declared that specific variable.
I have a hint that the issue is related to collation, case-sensitive or insensitive settings. Does anybody know how to resolve ?
Another situation where case sensitive variable names appear:
CREATE PROCEDURE Foo #customerID int AS
PRINT #customerId

You have a case sensitive server collation.
Your database has a (as you have shown) a case insensitive collation but when you have a case issue with variables it is the server collation that matters.
The same goes for sp_helptext which is a stored procedure defined in database master with lowercase. So when you call SP_HELPTEXT it is not found.
To fix your stored procedure to work in a case sensitive server collation you have to make sure that every reference to the variable #Variable1 is exactly that. Not #variable1 or #VARIABLE1.
Use this to check what server collation you have.
SELECT SERVERPROPERTY('collation');
From the SQL Server Books Online:
COLLATE (Transact-SQL)
The collation of an identifier depends on the level at which it is defined.
Identifiers of instance-level objects, such as logins and database names, are assigned the default collation of the instance.
Identifiers of objects within a database, such as tables, views, and column names, are assigned the default collation of the database.
For example, two tables with names different only in case may be created in a database with case-sensitive collation, but may not be created in a database with case-insensitive collation. For more information, see Database Identifiers.
The identifiers for variables, GOTO labels, temporary stored procedures, and temporary tables are in the default collation of the server instance.
Variables, GOTO labels, temporary stored procedures, and temporary tables can be created when the connection context is associated with one database, and then referenced when the context has been switched to another database.
See also
MSDN forums: Why are my SP's throwing a case error when pushing to a db using BIN collation?
Case sensitive variables in SQL Server
SQL Server stored procedure case sensitive?

Related

R SQL query: Could not find stored procedure

I am using R to run a stored SQL procedure:
query.str = "EXEC [StoredProcedure].[Procedure1]"
con <- odbcConnect("my_database")
my_data = sqlQuery(con, query.str)
This code works fine on my laptop. But when I try to run it on the server it gives an error:
42000 2812 [Microsoft][ODBC SQL Server Driver][SQL Server]Could not find stored procedure
I don't think this is a problem with the stored procedure itself, as I have encountered the same situation with multiple stored procedures (they work on my laptop but not the server).
Edit: I am sure the connection string works. When I use the same connection string for a non-stored-procedure, it works and data reads in just fine. The problem only occurs with stored procedures.
Thank you in advance!
Solution found: going through the Window Odbc connector, changing the default database to be the desired database fixed the problem.
This error may raise due to three main issues:
Incorrect reference of object's encapsulation including schema or database.
Every SQL Server object (table, stored procedure, function, etc.) resides in a schema and every schema resides in a database. Also, every object can be referenced by multi-part names. The default schema in SQL Server is dbo. Therefore by not specifying the database and schema in object reference, object is assumed to reside in connecting database and dbo schema. Consequently, below calls are equivalent:
EXEC [myServer].[myConnectedDatabase].[dbo].[myStoredProcedure]
EXEC [myConnectedDatabase].[dbo].[myStoredProcedure]
EXEC [dbo].[myStoredProcedure]
EXEC [myStoredProcedure]
If myStoredProcedure does not reside in either specified database or schema, this error would raise. If you do not know or remember where stored procedure resides, run queries on system sys views, INFORMATION_SCHEMA views, or system stored procedures, sp_*.
Incorrect spelling of stored procedure including not escaping special characters or reserved words.
To escape spaces, special characters (non-alphanumeric and non-underscore), and reserved words, enclose object names in square brackets [...]. Even better avoid such names. Thankfully for you, by default SQL Server is not case sensitive regarding identifiers. In other RDBMS's, like Oracle and Postgres, case sensitivity is retained for mixed cases during CREATE TABLE stage and double quotes would be needed for mixed cases types (i.e., "myStoredProc" <> mystoredproc <> MYSTOREDPROC).
Non-existent object in database or schema either by deletion or transfer to a different database or schema.

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).

SQL procedure vs. script - terminology [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 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.

Does naming function in MSSQL like fn_myFuction take additional performace

Someone here mentioned that We should avoid naming stored procedures in MS SQL server like sp_XXX
Because that taking addition time to SQL server while check does exist system sotred procedure named like that. Because all system stored procs are starting with sp_.
Now I wondering is that a case with Functions in MSSQL, Does naming functions like fn_ take additional time to SQL while looking for system functions ?
No, I don't think so.
Found the following thread:
http://bytes.com/topic/sql-server/answers/78872-udf-starting-fn_
No. To call a system-supplied [User Defined Function], you
need to use ::, so that is what SQL
Server looks for. All system-supplied
UDFs are table functions, as scalar
system functions are not UDFs at all.
Hope this helps
For functions it does not matter, however it is recommended to NOT use a prefix of sp_ for stored procedures as it defines a system stored procedure and may cause an extra lookup in the MASTER database.
As sp_ prefix is reserved for system
stored procedure and any stored
procedure which has sp_ prefix will
cause an extra lookup in MASTER
database. There is another point to
note that if a stored procedure uses
same name, in user database as system
stored procedure in master database,
the stored procedure in user database
will never get executed as SQL Server
will always look first in master
database and will execute that one
rather one in user database.
http://furrukhbaig.wordpress.com/2007/08/22/stored-procedures-factssheet/
http://msdn.microsoft.com/en-us/library/dd172115.aspx

Sql server 2005 acting case sensitive inspite of case insensitive collation

I am having following issue.Even after case insensitive collation. SQL server is treating #Result and #result differently. Am i missing something.Please help.
SELECT DATABASEPROPERTYEX('OA_OPTGB_0423', 'Collation') SQLCollation;
SQL_Latin1_General_CP1_CI_AS
DECLARE #Result varchar(2000)
SELECT TOP 1 #result = addr.address_id
FROM dbo.address addr
JOIN dbo.company_address compadd ON addr.address_id = compadd.address_id
ORDER BY addr.address_id desc
...throws this error:
Msg 137, Level 15, State 1, Line 2
Must declare the scalar variable "#result".
Edit:-
This same query works in my local machine.I tried it and got no error.
From MSDN:
Identifier Collation
The collation of an identifier depends
on the level at which it is defined.
Identifiers of instance-level objects,
such as logins and database names, are
assigned the default collation of the
instance. Identifiers of objects
within a database, such as tables,
views, and column names, are assigned
the default collation of the database.
Variables, GOTO labels, temporary
stored procedures, and temporary
tables can be created when the
connection context is associated with
one database and then referenced when
the context has been switched to
another database. Therefore, the
identifiers for variables, GOTO
labels, and temporary tables are in
the default collation of the instance.
So even though you're attempting to declare the collation of the database, variables are always going to use the default collation of your SQL Server instance.
If you've just reinstalled your database into a new instance, you should consider either upgrading your code to comply with the new collation (probably what I would do), or else follow this document on how to change the instance collation.
Really though, it seems a bit sloppy to have randomly cased variable references ;)
Collation deals with data (values); not identifier names.
There is no reason for your sample to fail unless you're running the statements as separate batches as your declarations only have scope local to the batch.
If you're running the statements one-at-a-time .... there's your problem!
Otherwise check what you have configured as a batch separator; the default is GO