测试
--------------------------------------------------------------------------------
Workershiftid ShiftID Startdate EntityId EndDate
--------------------------------------------------------------------------------
149 1 2016-08-01 00:00:00 1 2016-08-31 00:00:00
150 2 2016-08-01 00:00:00 4 2016-08-31 00:00:00
151 3 2016-08-01 00:00:00 5 2016-08-31 00:00:00
152 4 2016-08-01 00:00:00 7 2016-08-31 00:00:00
--------------------------------------------------------------------------------
我期待输出像
--------------------------------------------------------------------------------
Workershiftid ShiftID Startdate EntityId EndDate
--------------------------------------------------------------------------------
153 1 2016-09-01 00:00:00 1 2016-09-31 00:00:00
154 2 2016-09-01 00:00:00 4 2016-09-31 00:00:00
155 3 2016-09-01 00:00:00 5 2016-09-31 00:00:00
156 4 2016-09-01 00:00:00 7 2016-09-31 00:00:00
--------------------------------------------------------------------------------
我正在运行此查询:
declare @start datetime
declare @end datetime
SELECT @start = DATEADD(month, DATEDIFF(month, 0, getdate()), 0)
SELECT @end = DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0))
insert into test(workershiftid, shiftid, startdate, entityid, enddate)
select
workershiftid, shiftid, @start, entityid, @end
from
test
where
startdate = '2016-08-01'
但是我收到了一个错误:
违反PRIMARY KEY约束'PK_M_AttendanceWorkerShift'。无法在对象'dbo.M_AttendanceWorkerShift'中插入重复键。
我知道workershiftid是主键,它不允许重复。我想知道如何解决这个问题
答案 0 :(得分:2)
假设您在PK上有IDENTITY(workershiftid)...
您需要从插入脚本中删除workershiftid,因为sql server会自动为所有新行生成一个新的workerhiftid
最终剧本:
insert into [dbo].[test](EntityID, startdate,shiftid, IsGroup, EndDate)
select EntityID,@start, shiftid, IsGroup, @end
from [dbo].[test]
where startdate='2016-08-01'
答案 1 :(得分:0)
解决此问题的典型方法是将主键列声明为identity
列,并让数据库提供值。然后它不会包含在update
。
这个解决方案对你有用吗?