我有一个查询,该查询将SQL Server 2008 R2 Express中的7个表与总共852列连接在一起。 我试图用该查询的输出创建一个新表
尝试使用INTO,但由于表中的某些列具有重复名称,因此无法正常使用
USE VistaBI
SELECT *
INTO NewTable
FROM dbo.Agente FULL JOIN
dbo.Cte ON dbo.Agente.Agente = dbo.Cte.Agente
FULL JOIN
dbo.CteEnviarA ON dbo.Agente.Agente = dbo.CteEnviarA.Agente
FULL JOIN
dbo.Unidad ON dbo.CteEnviarA.Unidad = dbo.Unidad.Unidad
FULL JOIN
dbo.Venta ON dbo.Agente.Agente = dbo.Venta.Agente
FULL JOIN
dbo.VentaD ON dbo.Agente.Agente = dbo.VentaD.Agente
FULL JOIN
dbo.Art ON dbo.VentaD.Articulo = dbo.Art.Articulo
FULL JOIN
dbo.Alm ON dbo.Venta.Almacen = dbo.Alm.Almacen
有没有一种方法可以自动创建表,而不必用唯一的名称和数据类型键入852列中的每一个?
答案 0 :(得分:2)
我是动态完成的,请尝试以下代码:列名将变为表名+列名,因此不会重复任何列名。
User_ID Game_ID Like/Share Category Game_repeat Rating
1 11 1 1 2 4
1 22 2 1 0 3
1 33 0 0 0 0
2 33 1 0 0 1
2 44 2 0 0 2
2 11 0 0 0 0
答案 1 :(得分:0)
显式选择列名,而不使用*
在下面,我使用两个表
select
a.person_id,
a.city,
city.city_id
into
mytable
from
table1 a
inner join
city on a.city = city.city
所以就您而言
SELECT table_name.col1,table_nae.col2..... use explicitly column name in selection
INTO NewTable
FROM dbo.Agente FULL JOIN
dbo.Cte ON dbo.Agente.Agente = dbo.Cte.Agente
FULL JOIN
dbo.CteEnviarA ON dbo.Agente.Agente = dbo.CteEnviarA.Agente
FULL JOIN
dbo.Unidad ON dbo.CteEnviarA.Unidad = dbo.Unidad.Unidad
FULL JOIN
dbo.Venta ON dbo.Agente.Agente = dbo.Venta.Agente
FULL JOIN
dbo.VentaD ON dbo.Agente.Agente = dbo.VentaD.Agente
FULL JOIN
dbo.Art ON dbo.VentaD.Articulo = dbo.Art.Articulo
FULL JOIN
dbo.Alm ON dbo.Venta.Almacen = dbo.Alm.Almacen
答案 2 :(得分:0)
您可以做的是首先创建一个表,然后使用动态alter语句添加所需的列数:
public void nextSong() {
index += 1;
mediaPlayer.stop();
if (index > songs.listOfFiles.size() - 1) {
index = 0;
}
hit = new Media(songs.listOfFiles.get(index).toURI().toString());
mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
changeTitle();
}
if(mediaPlayer.getStatus() == MediaPlayer.Status.STOPPED){
nextSong();
}
然后只需将插入语句更改为:
CREATE TABLE MYTABLE
(
A INT,
B INT
)
DECLARE @I INT = 1, @COLNAME VARCHAR(20),@SQL VARCHAR(MAX)
WHILE (@I < 852)
BEGIN
SET @COLNAME = CAST(@I AS VARCHAR(20))
SET @SQL ='
ALTER TABLE MYTABLE
ADD [' + @COLNAME + '] VARCHAR(MAX);'
PRINT @SQL
EXEC(@SQL)
SET @I = @I + 1
END
这将为您提供列名称为1,2,3 ....等的结果,但这是一个动态名称,使您不必手动命名列。