插入SELECT,复合主键失败SQL Server 2008

时间:2012-06-11 15:32:02

标签: sql tsql

我有一个非常大的,未规范化的表,我正在修复它。从那张大表中我正在规范化数据。我使用了SQL语句

INSERT INTO smallTable(patientID, admissionDate, dischargeDate)
select distinct patientID, admissionDate, dischargeDate
FROM largeTable

所以我的smallTable填充了正确的行数。还有一个专栏drgCode,我想添加到我的smallTable中。我尝试了以下查询来做到这一点

INSERT INTO smallTable(drgCode)
select drgCode from
(
SELECT DISTINCT patientID, admissionDate, dischargeDate, drgCode from largeTable) as t

我收到的错误是cannot insert the value NULL into patientID, column does not alloq nulls, insert fails

正确选择drgCode的唯一方法是使用select distinct查询的某些变体。如果必须包含其他字段以缩小搜索范围,我如何只插入一个字段。

我知道如果我清空了我的smallTable,我可以做到这一点,但我认为必须要解决这个问题。

3 个答案:

答案 0 :(得分:5)

    with    drg as (SELECT DISTINCT patientID, admissionDate, dischargeDate, drgCode from largeTable)
    update  s
    set     s.drgCode = l.drgCode
    from    smallTable s join drg l on 
                s.patientId = l.patientId and
                s.admissionDate = l.admissionDate and
                s.dischargeDate  = l.dischargeDate

答案 1 :(得分:2)

根据我的理解,如果你有" PatientID"要在两个表中都是唯一的,您可以执行以下操作。

Update S
SET S.drgCode = L.drgCode
FROM
    SmallTable S
INNER JOIN
    LargeTable T
   ON S.PatientID = T.PatientID

希望这有助于!!

答案 2 :(得分:1)

对表执行插入操作时,查询中未指定的任何值都将使用列的默认值进行包装。如果列上没有默认值,则将使用NULL。您收到了该特定错误消息,因为您的列不允许NULL并且没有默认值。

鉴于你对Praveen的回复,也许你应该进一步规范并将drgCodes放到一个单独的表中。