使用String Builder,我需要检查我的应用程序中3个字段中的文本是否已插入数据库表中的3个相应列中,然后再插入其中任何一个。
首先,我将3个字段中的文本放入名为LastName,StreetAddress和ZipCode的对象属性中。然后我创建了我的参数。我这样做了:
var sb = new StringBuilder();
sb.Append("DECLARE @countLastName INT;");
sb.Append("DECLARE @countStreetAddress INT;");
sb.Append("DECLARE @countZipCode INT;");
sb.Append("SELECT @countLastName = COUNT (*) FROM tblCustomer WHERE LastName = @LastName;");
sb.Append("SELECT @countStreetAddress = COUNT (*) FROM tblCustomer WHERE StreetAddress = @StreetAddress;");
sb.Append("SELECT @countZipCode = COUNT (*) FROM tblCustomer WHERE ZipCode = @ZipCode;");
if (@countLastName < 1 || @countStreetAddress < 1 || @countZipCode < 1)
{
sb.Append("INSERT INTO tblCustomer (");
sb.Append("LastName, ");
sb.Append("StreetAddress, ");
sb.Append("ZipCode) ");
sb.Append("VALUES (@LastName, @StreetAddress, @ZipCode) ");
}
else
{
[Code that results in 1 of 3 messages being displayed to user based on which field is already in database. IE "LastName already exists"]
}
reader.CommandText = sb + "";
}
reader.Execute();
我将String Builder分配给了我的reader.CommandText,然后做了一个reader.Execute();,因为我已经完成了所有数据库命中。
Visual Studio并不喜欢我将@count变量放入我的IF语句中。在每一个下面都有一条红色的波浪线。
那么在插入我的值之前,如何使用String Builder检查我的计数变量是否小于1?
谢谢!
答案 0 :(得分:0)
好吧,你不能在StringBuilder中执行,但你可以改变命令在SQL Server中做整个逻辑。
例如,我会这样做(忽略哪个列是重复的):
IF(select COUNT (*) FROM tblCustomer WHERE LastName = @LastName or StreetAddress = @StreetAddress or ZipCode = @ZipCode) = 0 BEGIN
INSERT INTO tblCustomer (LastName, StreetAddress, ZipCode) VALUES (@LastName, @StreetAddress, @ZipCode)
END
在使用ExecuteNonQuery方法执行此操作后,我将在返回值中获得受影响的行计数,并知道是否进行了任何插入。 (请注意,触发器可能会更改受影响的行数)
另一种方法是更改检查和选择结果值的命令(如0:ok,1:姓氏已存在,2:地址已存在等)。这样您就可以使用ExecuteScalar或ExecuteReader并获得选定的值作为结果。
IF(select COUNT (*) FROM tblCustomer WHERE LastName = @LastName) > 0 BEGIN
SELECT 1
END ELSE IF(select COUNT (*) FROM tblCustomer WHERE StreetAddress = @StreetAddress) > 0 BEGIN
SELECT 2
END ELSE IF(select COUNT (*) FROM tblCustomer WHERE ZipCode = @ZipCode) > 0 BEGIN
SELECT 3
END ELSE BEGIN
INSERT INTO tblCustomer (LastName, StreetAddress, ZipCode) VALUES (@LastName, @StreetAddress, @ZipCode)
SELECT 0
END
第三种方法是创建一个SP来完成上面的整个逻辑。
两种方法都没有使用StringBuilder,分配给command.CommandText的单个字符串就足够了我想..