通过了解SELECT命令来构建SQL UPDATE命令
本文关键字:命令 构建 SQL UPDATE 了解 SELECT 过了 | 更新日期: 2023-09-27 18:20:36
假设这是我的选择查询:
SELECT
CNDSC.NAME,
CNEA.ATRBT AS ATR,
ISNULL(CNEXTRA.CNVAL,'') AS CNVAL,
ISNULL(CNEXTRA.INRDR,'') AS INRDR
FROM
CNDSC
INNER JOIN CNEA
ON CNEA.ELEMS LIKE '%'+CAST(CNDSC.FNCELEM AS VARCHAR)+'%' AND
NOT CNEA.ELEMS LIKE '%1'+CAST(CNDSC.FNCELEM AS VARCHAR)+'%'
LEFT OUTER JOIN CNEXTRA
ON CNEXTRA.ATR LIKE CNEA.ATRBT AND
CNEXTRA.NAME LIKE @con
WHERE
CNDSC.NAME LIKE @con;
我正在使用C#将该查询的结果绑定到数据网格上。但是,当我尝试使用SQLDataAdapter的"自动更新"命令时,由于在我的选择中使用了多个表,我会遇到异常。
如果我想更新CNEXTRA.CNVAL表,那么UPDATE命令会是什么样子?如果CNVAL为空,我如何确保必须使用INSERT命令?
谢谢你的帮助。
根据您的SQL server版本,您可以使用MERGE而不是UPDATE。
类似于:
DECLARE @CNVAL varchar(100) = 'test'
DECLARE @ATRBT varchar(100) = 'some attribute'
DECLARE @CON varchar(100) = 'the name'
MERGE into CNEXTRA as target
USING ( VALUES( @CON, @ATRBT, @CNVAL))
AS source([Name], ATRBT, CNVAL)
ON (target.ATRBT = source.ATRBT)
AND (target.[Name] = source.[Name])
WHEN MATCHED THEN
UPDATE SET
CNVAL = source.CNVAL
WHEN NOT MATCHED THEN
INSERT([Name], ATRBT, CNVAL)
VALUES(source.[Name], source.ATRBT, source.CNVAL)
;
如果记录存在,则MERGE语句将执行更新,如果不存在,则执行插入。
我还没有测试过这段代码,但类似的东西应该可以工作。。。(但您需要编写自己的插入、更新和删除查询)
public static DataSet UpdateSqlRows(
string connectionString,
string selectQuery,
string insertQuery,
string updateQuery,
string deleteQuery,
DataSet dataSet)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = new SqlCommand(selectQuery, connection);
connection.Open();
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
// Assign your own Insert/Update/Delete commands
adapter.InsertCommand = new SqlCommand( insertQuery );
adapter.UpdateCommand = new SqlCommand( updateQuery );
adapter.DeleteCommand = new SqlCommand( deleteQuery );
//Without the SqlCommandBuilder this line would fail
adapter.Update(dataSet);
return dataSet;
}
}
}