开发者

From Visual Studio (C#) - How to indicate a DEFAULT value for a function while calling a sql server function

开发者 https://www.devze.com 2023-03-27 12:44 出处:网络
I have a sql server function that I would like to call from Visual C#. I want to us开发者_开发知识库e the DEFAULT value for one of the parameters. What value should I pass from Visual C# to accomplish

I have a sql server function that I would like to call from Visual C#. I want to us开发者_开发知识库e the DEFAULT value for one of the parameters. What value should I pass from Visual C# to accomplish this? Thanks, rkg


Assuming you mean something like this:

 @MySampleSqlParam VarChar(50) = NULL

Because it's an optional parameter (it has a default supplied), all you need to do is simply not include that parameter when you call the procedure. So just omit adding the SqlParameter to the SqlCommand.Parameters collection.


Try this :

cmd.Parameters.Add("@YourParameter", SqlDbTypes.YourType).Value = DBNull.Value;


I would pass a nullable type into the function. Just don't pass the parameter if it's null:

public void saveSomething(int? somethingID, string somethingName)
{
     if (somethingID.HasValue)
     {
         //add the parameter
     }         
}

And use a default value in the sproc:

@SomethingID INT = NULL

Obviously, you'll also need to add logic to ignore the condition when the parameter is null.


Seems like you are looking for optional parameter in SQL. just Google for optional parameter in SQL.

You can create a function with a preset value for the parameter as:

CREATE FUNCTION dbo.fnMyFunction
(
@Param1 INT,
@Param2 INT = 2 --Default Values is Set no need to get it from parameter
)
RETURNS ..
0

精彩评论

暂无评论...
验证码 换一张
取 消