Jaz*_*azz 4 sql sql-server sql-server-2012
我有一个公司表和一个许可证表。我需要为公司表中尚未出现在许可证表中的每个公司在许可证表中插入一个新行。
License (ID,CompanyID,LicenseStart,LicenseEnd,CreatedDate,AddUser,UpdateUser,UpdateDate,TemplateId)
添加新行时,此表中的 ID 增加 1。
Company (ID,Name,CreateDate,CState,LocationID,LegalName)
将为不在许可证表中的每个 CompanyID 输入的默认值应如下所示。
Insert (ID, @theCompanyID, GetDate(), DATEADD(day,14,GETDATE()), null,null,null,null null)
@theCompanyID 将是不在许可证表中的 CompanyID
我对此很陌生,因此将不胜感激。
license.id 是一个标识列,因此您不需要插入它。
insert into license (CompanyID, LicenseStart, LicenseEnd)
select c.id, GetDate(), DATEADD(day, 14, GETDATE())
from company c
where not exists (select 1
from license l
where c.ID = l.CompanyID
);
Run Code Online (Sandbox Code Playgroud)
您也不需要为NULL未提供值的列插入显式值。默认设置是将这些值设置为NULL。
如果您的开始日期和结束日期没有时间组件——只有日期——那么请改用它:
select c.id, cast(GetDate() as date), cast(DATEADD(day, 14, GETDATE()) as date)
from company c
where not exists (select 1
from license l
where c.ID = l.CompanyID
);
Run Code Online (Sandbox Code Playgroud)