Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Setting a SQL Server Bit to "false" in a stored procedure definition valid?

Bits are often used in SQL Server to represent true and false however you cannot literally assign true and false to them it must be 1 or 0.

I recently stumbled across the following code:

CREATE PROCEDURE TestProcedure
@parameter bit = false
AS
BEGIN
...
END

Why is it valid? Especially when setting a bit to false in the body of the stored procedure is not.

If you query the parameter with a select it is indeed set to 0 which represents false.

like image 736
Three Value Logic Avatar asked Feb 10 '15 11:02

Three Value Logic


People also ask

What is true regarding stored procedures in SQL?

Stored procedures in SQL Server can accept input parameters and return multiple values of output parameters; in SQL Server, stored procedures program statements to perform operations in the database and return a status value to a calling procedure or batch.

Why are stored procedures not secure?

Conclusion. As seen from the process above, stored procedures are a secure and safe way to give access to your database. That means someone can only be able to do what is defined in stored procedures that you have given him permission to call. And that makes stored procedures great for securing data in a database.

How do you assign a bit value in SQL?

To insert a new value to the BIT column, use INSERT statement: INSERT INTO table_name (bit_column) VALUES (1); You can also use TRUE and FALSE as the inputs for the BIT columns, SQL Server will automatically convert them as follow: TRUE will be converted to 1.


1 Answers

SQL Server has in built functionality to convert string values 'true' to 1 and 'false' to 0:

Run this code and see:

DECLARE @someval BIT = 'true'

SELECT @someval

SET @someval = 'false'

SELECT @someval

Reference:

bit (Transact-SQL)

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

As @hvd states in comments, the reason the declaration works without quotes in your sample is based on quotes being optional in parameter assignments of a stored procedure declaration.

Reference:

Parameter Assignment to unquoted string

In a stored procedure definition, a parameter can be assigned a default string value that is an 'unquoted' string.

...this is very widely used legacy behavior that needs to be maintained for compatibility reasons. The same behavior can be seen when passing parameters in an exec statement.

like image 128
Tanner Avatar answered Sep 28 '22 02:09

Tanner