Sql server 如果存在数据来自不同位置且可编辑的表,如何插入或替换该表
我想不出解决的办法所以我问了这个问题 让我们先从一开始解释一下 我有这张桌子:Sql server 如果存在数据来自不同位置且可编辑的表,如何插入或替换该表,sql-server,Sql Server,我想不出解决的办法所以我问了这个问题 让我们先从一开始解释一下 我有这张桌子: tHoneyHarvest (RecID is PK and auto increment) RecID HarvestDate HoneyComb [etc] -------------------------------------------- 1 2017-01-30 5 2 2017-02-01 3.5 3
tHoneyHarvest (RecID is PK and auto increment)
RecID HarvestDate HoneyComb [etc]
--------------------------------------------
1 2017-01-30 5
2 2017-02-01 3.5
3 2017-01-25 2
4 2017-01-30 5
然后我通过以下方式从该表中获取数据:
select HarvestDate, HoneyType, Sum (HoneyComb) as TotalCombs
From tHoneyHarvest
group by HarvestDate,
order by HarvestDate
然后将其显示给用户,并通过显示它,为它的每一行从user获得一个名为HoneyWeight
的变量
现在我的问题是:
我想把这些数据插入这样的表中
tHoneyWeight (RecID is PK and auto increment)
RecID HarvestDate HoneyComb HoneyWeight
----------------------------------------------------
1 2017-01-30 10 20
2 2017-02-01 3.5 7
3 2017-01-25 2 4
它可以通过一个简单的插入来完成,但是如果用户想从tHoneyHarvest
返回并编辑HoneyWeight
,或者想编辑HoneyWeight
,该怎么办呢
这会导致在thoneywheet
中插入重复的行,如果要使用update,如何区分必须更新的行
很抱歉,如果这是一个很长的问题,但无法弄清楚我该怎么办
更新:
在C的帮助下,我找到了一种得到我想要的东西的方法#
首先,我创建这个过程
Create Procedure GetTotlCombByHarvDtHTyp
as
Select HarvestDate, HoneyType,SUM(HoneyComb) AS TotalCombs
From tHoneyHarvest
Group BY HarvestDate, HoneyType
Order BY HarvestDate DESC
然后将它的数据加载到c#中的数据表中,通过这个循环,我编辑tHoneyWeight
foreach (DataRow DR in Dtable.Rows)
{
using (SqlCommand SqlCmd = new SqlCommand())
{
SqlCmd.Connection = SqlCon;
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCmd.CommandText = "InsOrUpdtHoneyWt";
SqlCmd.Parameters.Add("@HarvestDate", SqlDbType.Date).Value = DR["HarvestDate"];
SqlCmd.Parameters.Add("@HoneyType", SqlDbType.VarChar, 50).Value = DR["HoneyType"];
SqlCmd.Parameters.Add("@TotalCombs", SqlDbType.Float).Value = DR["TotalCombs"];
SqlCmd.Parameters.Add("@RV", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
SqlCmd.ExecuteNonQuery();
}
}
存储过程是:
Create Procedure InsOrUpdtHoneyWt
@HarvestDate Date,
@HoneyType VarChar(50),
@TotalCombs Float
as
If NOT Exists (Select * From tHoneyWeight
Where (HarvestDate=@HarvestDate AND
HoneyType=@HoneyType))
begin
Insert INTO tHoneyWeight
(HarvestDate,
HoneyType,
TotalCombs)
Values(@HarvestDate,
@HoneyType,
@TotalCombs)
Return 1
end
else
begin
Update tHoneyWeight
Set TotalCombs=@TotalCombs
Where (HarvestDate=@HarvestDate AND
HoneyType=@HoneyType)
end
然后,我删除了tHoneyWeight中保留的额外行,因为tHonetHarvest中的删除或更新使用了我的:
我走了这么长的路,因为我不知道更好的方法,而且我确信随着行数的增加,这会使我的性能降低很多。首先创建一个新的列“HoneyWeight”,它可以有空值。
然后,如Tim所述,使用-
Update tHoneyHarvest
SET HoneyWeight = input_value
WHERE RecID = (1/2/3...);
谷歌搜索
更新SQL命令
。。。我想你只是想更新一下你的表格。使用WHERE
子句标识要更改的记录。如果这是一个显示实时数据的副本,为什么不使用视图?@TimBiegeleisen根据TotalCombs分配HoneyWeight,然后(分组收获日期、TotalCombs和HoneyWeight)插入到表中,但是,如果用户插入了另一个收割日期和蜂巢,该怎么办?如何在tHoneyWeight表中添加这一行,或者如果用户将某些梳子移动到另一个日期,如何编辑此表…@Viki888更新了问题