8

I have the following stored procedure

CREATE PROCEDURE [dbo].[usp_GetData]
@foo VARCHAR (20), @bar bit = 1
AS ...

This provides the correct result when called in SSMS.

EXEC dbo.usp_GetData @foo = 'Hellow World', @bar = 0

Although when calling within a C# application as per below

cmd.Parameters.Add(new SqlParameter("@foo", foo)); 
cmd.Parameters.Add(new SqlParameter("@bar", 0));

& is captured by the profiler as below.

exec dbo.usp_GetData @foo=N'Hello World',@bar=default

Does a parameter that overides the default have to be passed differently?

4
  • 2
    A bit is a boolean value what happens if you pass false instead of zero? Commented Sep 26, 2013 at 23:24
  • 1
    He is trying to pass 'false' for bit instead of the default. What happens if you try passing 'false' instead of '0'? Commented Sep 26, 2013 at 23:25
  • I want to provide a parameter & am in the above code but when the SQL is passed to the database it has default instead of 0 which is what I added for the @bar parameter @gunr2171 Commented Sep 26, 2013 at 23:26
  • Let me try @jcwrequests Commented Sep 26, 2013 at 23:26

3 Answers 3

4

Use

cmd.Parameters.AddWithValue("@bar", 0)

This way you know you actually passing the value.

Sign up to request clarification or add additional context in comments.

Comments

2

new SqlParameter("@bar", 0) triggers the wrong overload - string parameterName, SqlDbType dbType. The value ends up being not set.

You want the one that sets the value, so it's ought to be new SqlParameter("@bar", (object)0).

This is why AddWithValue was introduced.

6 Comments

How does 0 map to SqlDbType?
@gunr2171 Nicely. It maps to SqlDbType BigInt, and it's a better match than to an object as far as the compiler concerned.
I don't think I said it correctly. How does 0, an int, use the constructor form with a SqlDbType? Is there an implicit cast that allows this?
This worked fine but so did passing false. Is there any disadvantage using false as it just seems cleaner. @GSerg
@ojhawkins, your parameter is a bit, so providing the correct data type is always a good idea, instead of hoping sql will convert the integer correctly.
|
0

Better and safe :

cmd.Parameters.Add("@bar", SqlDbType.NVarChar, 16, "bar");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.