You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于C#与SQL Server的生产ERP多列数据验证表创建需求

解决SQL Server p1_order表的重复插入限制问题

1. 修正原表创建语句的语法错误

原语句存在两处语法问题:

  • prod_date date notnull 应为 prod_date date not null(关键字间需保留空格)
  • prod_qty, float not null 列定义顺序错误,正确写法是 prod_qty float not null

2. 添加联合唯一约束实现重复插入限制

要实现仅当prod_date、order_no、mach_no、shift_no、prod_type至少一个值不同时才能插入,只需给这5个列添加联合唯一约束,SQL Server会自动校验该列组合的唯一性,若组合值完全重复则拒绝插入操作。

最终的表创建语句如下:

create table p1_order(
    id int not null,
    order_no int not null,
    prod_date date not null,
    prod_type nvarchar(5),
    shift_no int not null,
    mach_no nvarchar(5) not null,
    prod_qty float not null,
    -- 联合唯一约束,限制指定列组合不能重复
    constraint UQ_p1_order_ProdCombination unique (prod_date, order_no, mach_no, shift_no, prod_type)
)

补充说明

  • 插入数据时,若指定的5个列组合值已存在于表中,SQL Server会抛出「违反唯一约束」的错误,直接阻止重复数据插入
  • 后续若需调整约束,可先执行ALTER TABLE p1_order DROP CONSTRAINT UQ_p1_order_ProdCombination删除现有约束,再重新创建新约束

内容的提问来源于stack exchange,提问作者Rv610

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:45:46