在这里度过一个完美的金发时刻,所以提前道歉......!
我想在输入记录到数据库中的新客户之前执行两个COUNT条件。以下代码检查用户名是否已被使用,如果适用,则拒绝注册。我想添加一个额外的COUNT来检查来自txtEmail的“CustomerEmail”是否已经存在于数据库中。
答案 0 :(得分:0)
而不是计算所有用户并添加2个检查,只需执行一个包含2个条件的存在语句。
IF NOT EXISTS(select count(*) from [Customer] where CustomerUserName= @name AND CustomerEmail = @email)
BEGIN
INSERT INTO [Customer] (CustomerFirstName,CustomerSurname,CustomerEmailAddress,CustomerAddress,CustomerAddressTown,CustomerAddressCity,CustomerAddressPostcode,CustomerContactNumber,CustomerUserName,CustomerPassword) VALUES (@FirstName, @Surname,@Email, @Address, @Town, @City, @Postcode,@ContactNumber,@Username,@Password)
END
答案 1 :(得分:0)
我会使用存储过程来执行这样的操作......
显然,为params使用适当的数据类型
CREATE PROCEDURE usp_InsertUser
@FirstName VARCHAR(100)
, @Surname VARCHAR(100)
, @Email VARCHAR(100)
, @Address VARCHAR(100)
, @Town VARCHAR(100)
, @City VARCHAR(100)
, @Postcode VARCHAR(100)
, @ContactNumber VARCHAR(100)
, @Username VARCHAR(100)
, @Password VARCHAR(100)
, @UserAdded INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS (SELECT *
FROM [Customer] WITH (UPDLOCK)
WHERE CustomerUserName = @Username)
BEGIN
INSERT INTO [Customer] (CustomerFirstName,CustomerSurname,CustomerEmailAddress,CustomerAddress,CustomerAddressTown,CustomerAddressCity,CustomerAddressPostcode,CustomerContactNumber,CustomerUserName,CustomerPassword)
VALUES (@FirstName, @Surname,@Email, @Address, @Town, @City, @Postcode,@ContactNumber,@Username,@Password)
SET @UserAdded = 1;
END
ELSE
BEGIN
SET @UserAdded = 0;
END
END
应用程序代码看起来像......
// define connection and command, in using blocks to ensure disposal
using(SqlConnection conn = new SqlConnection(pvConnectionString ))
using(SqlCommand cmd = new SqlCommand("dbo.usp_InsertUser", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("@UserAdded", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 100);
cmd.Parameters.Add("@Surname", SqlDbType.VarChar, 100);
cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100);
// and so on.....
// set parameter values
cmd.Parameters["@FirstName"].Value = txtFirstName.Text;
cmd.Parameters["@Surname"].Value = txtSurname.Text;
cmd.Parameters["@Email"].Value = txtEmail.Text;
// and so on.....
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from @NewId
int UserAdded = Convert.ToInt32(cmd.Parameters["@UserAdded"].Value);
if (UserAdded == 1)
{
Response.Write("User already exists.");
}
conn.Close();
}