Domanda

Today, a bug that was really hard to track down manifested itself in our project.

We had a trigger that performed certain actions when data was inserted or updated, including calling several stored procedures, and the program seemed to work correctly. Except when it didn't.

After hours of hair-tairing, we finally found the culprit: a missing "@" in front of a parameter name in an EXEC statement. The following minimal example shows the issue:

CREATE PROCEDURE EchoString @TheString nvarchar(30)
AS
SELECT @TheString 
GO

declare  @MyString char(10) = 'FooBar!'

exec EchoString @MyString
exec EchoString MyString -- Why does this work?

Now, this made me wonder: what is the purpose of allowing this? Is it only for backward compatibility, or are there legitimate use cases for this? Is it documented somewhere (my feeble googling turned up blank, but "@" is not all that google-able.)

È stato utile?

Soluzione

In some cases SQL Server will interpret such a parameter as a string. The most well-known example:

EXEC sp_who2 active;

Is the same as:

EXEC sp_who2 'active';

I don't know if this behavior is documented but writing code this way is certainly fragile IMHO.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top