iT邦幫忙

0

MS SQL 時間內限制人數輸入

設計一個預存程序檢核時間內輸入人數不超過2人
15分鐘為區段
有張表格Limittime欄位有兩個
欄位名稱 ID跟 Times

若未超過 insert 當下 最新排序ID 跟當下時間 Times
若超過就刪除原要輸入的當下時間那筆資料

原本是有寫出判斷時間區段的人數
超過顯示錯誤
未超過顯示符合

但是要有insert功能就卡住了@@

有大神可以幫忙解題下嗎?
手機排版希望可以了解我的意思?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
純真的人
iT邦大師 1 級 ‧ 2021-10-22 11:42:20
最佳解答

你參考~
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=517b4280b6b5caa0eaaf7d5e8b854b7b

create table Limittime(
  ID int
  ,Times datetime
)
insert into Limittime(
  ID,Times
)
select isNull((select max(ID) from Limittime),0) + 1 as ID
,GetDate() Times
where exists(
  select 0
  from Limittime
  where datediff(minute,Times,GetDate()) < 15
  having count(0) <= 1
)
select *
from Limittime
insert into Limittime(
  ID,Times
)
select isNull((select max(ID) from Limittime),0) + 1 as ID
,GetDate() Times
where exists(
  select 0
  from Limittime
  where datediff(minute,Times,GetDate()) < 15
  having count(0) <= 1
)
select *
from Limittime
insert into Limittime(
  ID,Times
)
select isNull((select max(ID) from Limittime),0) + 1 as ID
,GetDate() Times
where exists(
  select 0
  from Limittime
  where datediff(minute,Times,GetDate()) < 15
  having count(0) <= 1
)
select *
from Limittime
看更多先前的回應...收起先前的回應...

哇!我來研究一下感謝!本來以為要用if 判斷小於2才能 insert
但是一直出現錯誤說子查詢出來的值會不只一個無法判斷

原來不需要!還有這種寫法!太感謝了~~~

小魚 iT邦大師 1 級 ‧ 2021-10-22 13:18:17 檢舉

是不是...跳針了?

小魚
沒跳針唷@@~那是範例執行結果~
第1筆15分鐘內新增
第2筆15分鐘內新增
第3筆15分鐘內新增失敗~

小魚 iT邦大師 1 級 ‧ 2021-10-22 17:55:15 檢舉

喔喔, 原來是這樣子.

2
海綿寶寶
iT邦大神 1 級 ‧ 2021-10-22 11:33:09

原本是有寫出判斷時間區段的人數(判斷:大於2)
超過顯示錯誤
未超過顯示符合

改成

判斷時間區段的人數(判斷:大於1,因為還沒 INSERT)
超過-不要 INSERT
未超過- INSERT

即可

https://ithelp.ithome.com.tw/upload/images/20211022/20001787uWF81K7O4n.png

我要發表回答

立即登入回答