我想要做的就是在文本框为空时插入Null和数据库。
--ACCOUNT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET IDENTITY_INSERT account ON
INSERT INTO dbo.account
(
AccntID ,
managedby ,
AccountHolder ,
Description ,
AccountType ,
ContactPerson ,
ContactNumber ,
EmailAddress ,
Address ,
ClientTYpe ,
SchemeType ,
SalesManager ,
DateCreated ,
Login ,
Password ,
Balance ,
FilterOption ,
Enable22 ,
AllowExtendedConfig
)
-- Insert statements for procedure here
VALUES (@AccntID, @managedby, @AccountHolder, @Description, @AccountType, @ContactPerson, @ContactNumber, @EmailAddress, @Address, @ClientType, @SchemeType, @SalesManager, @DateCreated, @Login, @Password, @Balance, @FilterOption, @Enable22, @AllowExtendedConfig)
SET IDENTITY_INSERT account OFF
END
当我的文本框为空时,将NULL值添加到数据库的最佳方法是什么
答案 0 :(得分:1)
设置帮助函数,例如:
Public Function DbNullOrStringValue(ByVal value As String) As Object
If String.IsNullOrEmpty(value) Then
Return DBNull.Value
Else
Return value
End If
End Function
因此,第一个代码块将通过调用它来简化:
Cmd.Parameters.AddWithValue("@AccntID", DbNullOrStringValue(TextBox1.Text))
Cmd.Parameters.AddWithValue("@managedby", DbNullOrStringValue(TextBox2.Text))
Cmd.Parameters.AddWithValue("@AccountHolder", DbNullOrStringValue(TextBox3.Text))
Cmd.Parameters.AddWithValue("@Description", DbNullOrStringValue(TextBox4.Text))
Cmd.Parameters.AddWithValue("@AccountType", DbNullOrStringValue(TextBox5.Text))
Cmd
是您的SqlCommanad
对象
答案 1 :(得分:1)
考虑比新方法更轻松的东西:
Cmd.Parameters.AddWithValue("@AccntID", IIF(String.IsNullOrEmpty(TextBox1.Text), DBNull.Value, TextBox1.Text))
但对于其他人,请按照之前的建议使用SqlDataAdapter
。
答案 2 :(得分:0)
最好的方法是继承文本框并为其添加其他功能
Public Class MyText
Inherits TextBox
'Either change default text property (but this will bug you while comparing text property)
Public Overrides Property Text() As String
Get
Return MyBase.Text
End Get
Set(ByVal value As String)
MyBase.Text = value
End Set
End Property
'Best way will be to write new property to use in sql query
Public ReadOnly Property TextSQL() As String
Get
If Me.Text = String.Empty Then
Return "NULL"
Else
Return Me.Text
'Return "'" & Me.Text & "'" 'or this
End If
End Get
End Property
End Class
现在在您的应用程序中使用此文本框
cmd.Parameters.AddWithValue("@accountholder", txt_accHolder.TextSQL)
答案 3 :(得分:0)
在存储过程中,您可以使用以下命令:
假设:参数名称是@TextData
NULLIF(LTRIM(RTRIM(@TextData)),'')
如果@TextData ='',它将返回NULL。