简体   繁体   English

默认等效于DBNull.Value

[英]Default Equivalent to DBNull.Value

I am trying to pass default to SQL Server in c#. 我试图在c#中将默认值传递给SQL Server。

This code passes null. 此代码传递null。 Is there any way to pass default? 有没有办法通过默认?

foreach (SqlParameter Parameter in command.Parameters)
{
    if (Convert.ToString(Parameter.Value) == "")
    {
        Parameter.Value = DBNull.Value;
    }
}

Either don't add the parameter, or add the parameter but set the value to null ( not DBNull.Value ). 要么不添加参数,要么添加参数,但将值设置为null而不是 DBNull.Value )。 Both have the same effect: the parameter is not passed, therefore the default is used. 两者都具有相同的效果:参数未传递,因此使用默认值。

You can set the parameter default in SQL-Server (Stored Procedure...) 您可以在SQL-Server中设置参数default(存储过程...)

(@parm varchar(5) = null)
AS
Begin...

And then don't pass the parameter from C# at all. 然后不要从C#传递参数。

Here is another solution of sorts -- it appears to search the stored procedure for parameter default values (literally, a pattern search for the assignment in the declaration of the variable), and return any default values that are found. 这是另一种解决方案 - 它似乎在搜索存储过程中查找参数默认值(字面意思是在变量声明中对赋值进行模式搜索),并返回找到的任何默认值。 So...you could call this procedure from your c# app to get all of your default values, assign them to local C# vars, and then use them when you call your other procedure. 所以...你可以从你的c#app调用这个程序来获取所有默认值,将它们分配给本地C#变量,然后在调用其他过程时使用它们。

http://www.codeproject.com/Articles/12939/Figure-Out-the-Default-Values-of-Stored-Procedure http://www.codeproject.com/Articles/12939/Figure-Out-the-Default-Values-of-Stored-Procedure

And here is how you could find the default value on a table itself: (you might need to strip the parenthesis off the returned value) 以下是如何在表本身上找到默认值:(您可能需要从返回值中删除括号)

SELECT COLUMN_DEFAULT, replace(replace(COLUMN_DEFAULT,'(',''),')','') as DefaultWithNoParenthesis
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'WHATEVER'

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM