create table T1
(
Name varchar(50),
Address varchar(50),
Tel varchar(50)
);
create table T2
(
ParamName varchar(50),
ParamValue Varchar(60),
TableName varchar(50)
);
insert into T2 values('Name', 'test', 'Member');
insert into T2 values('Address', 'testAdd', 'Member');
insert into T2 values('Tel', 'test', 'Member');
insert into T1(Select distinct ParamName from T2)
values(select ParamValue from T2 )
我正在寻找一种方法,通过从T2表中获取值和列名来插入T1表。需要从T2表获取列名,将值添加到该特定列
答案 0 :(得分:2)
您可以使用:
INSERT INTO T2(Column1,Column2)
SELECT Column1, Column2 FROM T1
GROUP BY Column1;
答案 1 :(得分:2)
您可以尝试在T2
上使用数据透视查询,将名称,地址和电话号码放到每个表名的一行中。然后,只需使用INSERT INTO ... SELECT
,除了使用透视结果。
INSERT INTO T1 (Name, Address, Tel)
SELECT
MAX(CASE WHEN ParamName = 'Name' THEN ParamValue END) AS Name,
MAX(CASE WHEN ParamName = 'Address' THEN ParamValue END) AS Address,
MAX(CASE WHEN ParamName = 'Tel' THEN ParamValue END) AS Tel
FROM T2
GROUP BY TableName
-- WHERE TableName IN ('Member', ...)
如果要将插入限制为某些表名,可以取消注释WHERE
子句。
作为一般性评论,如果您这样做是为了让您的数据更加规范化,那么我认为这很好。但是,如果您计划长期存储数据,则可能需要重新考虑您的表格设计。
答案 2 :(得分:1)
你的表格结构没有多大意义。表之间没有明显的逻辑关系。第二个只是缓冲表吗?
但是,无论如何,如果要将表中的值插入到另一个表中,可以这样做:
INSERT INTO [target_table] ([target_column_1], [target_column_2], ..., [target_column_n])
SELECT [source_column_1], [source_column_2], ..., [source_column_n]
FROM [source_table]
WHERE [conditon]
答案 3 :(得分:0)
我觉得你看起来像..
INSERT INTO T1(Name)
SELECT DISTINCT ParamName FROM T2
答案 4 :(得分:-1)
DECLARE @TableName varchar(50) = 'T1'
DECLARE @ColumnName varchar(MAX)
SELECT @ColumnName= coalesce(@ColumnName + ', ', '') + a.COLUMN_NAME
from (SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
inner join T2 on TableName = TABLE_NAME
WHERE TABLE_NAME = @TableName and ParamName = COLUMN_NAME) a;
print @ColumnName
declare @ParamName varchar(MAX)
SELECT @ParamName = coalesce(@ParamName + ', ', '') + ''''+a.ParamValue+''''
from (SELECT COLUMN_NAME,ParamValue
FROM INFORMATION_SCHEMA.COLUMNS
inner join T2 on TableName = TABLE_NAME
WHERE TABLE_NAME = @TableName and ParamName = COLUMN_NAME) a;
print @ParamName
declare @QUERY nvarchar(MAX);
SET @QUERY = 'INSERT INTO T1 ('+@ColumnName+')
VALUES ('+@ParamName+')'
EXEC sp_executesql @QUERY
这就是我所期待的答案,感谢所有人的帮助