我希望使用以下update \ insert方法来加速我的应用程序insert \ updates:
UPDATE [Application_Type_Table]
SET ApplicationType='Test Value'
WHERE ID='1'
IF @@ROWCOUNT=0
INSERT INTO [Application_Type_Table] VALUES ('Test Value')
我如何使用sql参数执行此操作?由于@@。
,rowcount函数将被选为参数sqlCommand.CommandText = _
"UPDATE [Application_Type_Table]" _
SET (SET ApplicationType=@TestValue" _
"WHERE ID=@RecordID IF @@ROWCOUNT=0 INSERT INTO [Application_Type_Table] VALUES (@TestValue)"
http://blogs.msdn.com/b/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx
答案 0 :(得分:4)
此模式称为UPSERT。这样做的现代方法是在SQL Server 2008中使用MERGE,例如
MERGE INTO Application_Type_Table AS target
USING (
VALUES (@RecordID, @TestValue)
) AS source (ID, ApplicationType)
ON target.ID = source.ID
WHEN MATCHED
THEN UPDATE
SET ApplicationType = source.ApplicationType
WHEN NOT MATCHED
THEN INSERT (ID, ApplicationType)
VALUES (ID, ApplicationType);
答案 1 :(得分:0)
sqlCommand.CommandText = "IF NOT EXISTS (SELECT 1 FROM [Application_Type_Table] WHERE "_
"ID='1') BEGIN INSERT INTO " _
"[Application_Type_Table] VALUES ('Test Value') END ELSE BEGIN UPDATE [Application_Type_Table]"_
"SET ApplicationType='Test Value'"_
"WHERE ID='1' END"
答案 2 :(得分:-1)
我建议将查询移动到存储过程。查询(尤其是多语句查询)实际上并不属于硬编码到一个应用程序IMO中。这样做也可以减轻你的问题;)