Sql 将日期从一个表复制到其他表的最佳方法
我有这张桌子: 身份证件 名字 角色 1 汤姆 行政 2 汤姆 使用者 三 约翰 行政 您可以使用以下查询:Sql 将日期从一个表复制到其他表的最佳方法,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有这张桌子: 身份证件 名字 角色 1 汤姆 行政 2 汤姆 使用者 三 约翰 行政 您可以使用以下查询: insert into user (name) select distinct name from following; insert into userrole (userid, roleid) select u.userid, f.roleid from following f join user u on f.n
insert into user (name)
select distinct name
from following;
insert into userrole (userid, roleid)
select u.userid, f.roleid
from following f join
user u
on f.name = u.name;
这些可以合并到存储过程中。您也可以尝试合并添加、更新和删除。Merge使用复合索引或主键查找匹配行。这是etl的一种数据仓库方式。您可能必须将主键的标识设置为off
use MyDataDB
declare @Output as varchar(max)
declare @ColumnName as varchar(100)
declare @TableName as varchar(30)='your_table_name'
declare @UpdateStatement as varchar(max)=''
declare @InsertStatement as varchar(max)=''
declare @InsertStatement2 as varchar(max)=''
declare @DeleteStatement as varchar(max)=''
Declare @Join as varchar(max)
declare @JoinColumns Table(ColumnName varchar(50))
---- Add your primary Key here or composite index
Insert into @JoinColumns(ColumnName)
values('YourKeyID')
select @Join=
(select ' AND TARGET.'+ColumnName+'=SOURCE.'+ColumnName from @JoinColumns for xml path(''))
select @Join=right(@Join,len(@Join)-5)
declare c1 cursor
for
SELECT
COLUMN_NAME
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = @TableName
open c1
fetch next from c1 into @ColumnName
set @Output=N'MERGE ReportData.dbo.'+ @TableName + ' as TARGET USING ReportData.dbo.' + @TableName + '_Stage as SOURCE ON
(' + @Join +') WHEN MATCHED THEN ';
set @UpdateStatement=N' UPDATE SET ';
set @InsertStatement =N' WHEN NOT MATCHED BY TARGET THEN INSERT(';
set @InsertStatement2=N' Values(';
set @DeleteStatement=N' WHEN NOT MATCHED BY SOURCE THEN DELETE';
while @@FETCH_STATUS=0
begin
if not exists(select '' from @JoinColumns where ColumnName=@ColumnName)
begin
if @UpdateStatement=N' UPDATE SET '
SET @UpdateStatement=@UpdateStatement + 'TARGET.' + @ColumnName+'='+'SOURCE.'+@ColumnName
else
SET @UpdateStatement=@UpdateStatement + ',TARGET.' + @ColumnName+'='+'SOURCE.'+@ColumnName
end
if @InsertStatement =N' WHEN NOT MATCHED BY TARGET THEN INSERT('
BEGIN
Set @InsertStatement=@InsertStatement+@ColumnName
Set @InsertStatement2=@InsertStatement2+'SOURCE.'+@ColumnName
END
ELSE
BEGIN
Set @InsertStatement=@InsertStatement+','+@ColumnName
Set @InsertStatement2=@InsertStatement2+',SOURCE.'+@ColumnName
END
fetch next from c1 into @ColumnName
end
close c1
deallocate c1
SET @Output=@Output + @UpdateStatement
SET @Output=@Output + @InsertStatement+') '
SET @Output=@Output + @InsertStatement2+') '
SET @Output=@Output + @DeleteStatement+';'
select @Output