为多列创建表语句

时间:2015-12-18 10:36:06

标签: sql sql-server

如果我在T-SQL中执行如下所示的创建表,则基于之前存在的select语句:

create table #CodesToVoid
(
        PromotionId int, 
        PromotionId int, 
        Code nchar(10), 
        BookingReference nvarchar(50)   
)

INSERT #CodesToVoid
   SELECT 
       p.PromotionId [MasterPromotionID], 
       pc.PromotionId, pc.Code, pc.BookingReference  
   FROM
       J2H.dbo.Promotions p...

我觉得必须使用升级ID,因为一个来自别名p.而另一个来自别名pc.如果在创建表语句中我将其中一个PromotionId称为:

PromotionId [MasterPromotionID] int

显示语法错误。如果我这样做,那就相同:

PromotionId AS MasterPromotionID int

我的问题是在这种情况下我需要在create table中使用两个promoteId,因为select语句有两个这样的吗?

2 个答案:

答案 0 :(得分:4)

2列不能使用相同的idenfitifier。创建表格为:

CREATE TABLE #CodesToVoid(
        MasterPromotionID INT, 
        PromotionId INT, 
        Code NCHAR(10), 
        BookingReference NVARCHAR(50));

INSERT INTO #CodesToVoid(MasterPromotionID,PromotionId,Code,BookingReference)
SELECT p.PromotionId,      -- aliasing change nothing here 
   pc.PromotionId,         -- data will be inserted to column specified in column list
   pc.Code,
   pc.BookingReference  
FROM J2H.dbo.Promotions p...

<小时/> 或者使用SELECT * INTO

SELECT p.PromotionId [MasterPromotionID],
       pc.PromotionId,
       pc.Code,
       pc.BookingReference  
INTO #CodesToVoid
FROM J2H.dbo.Promotions p...

请注意,多次创建SELECT * INTO ...可能会返回当前连接所存在的表的错误。

答案 1 :(得分:1)

如果您首先使用“创建表格”,那么该表中的字段名与您选择中的fieldNames无关。他们在位置匹配。即:

create table #CodesToVoid
        (
        MasterPromoId int, 
        PromoId int, 
        Code nchar(10), 
        BookingReference nvarchar(50)   
        );

INSERT #CodesToVoid
SELECT p.PromotionId, pc.PromotionId, pc.Code, pc.BookingReference  
from J2H.dbo.Promotions p...

但是,对于这样的事情,你不会先创建一个表。你只需“选择进入”一张桌子。它为您创建“创建表”部分。即:

SELECT p.PromotionId as [MasterPromotionID], 
   pc.PromotionId, 
   pc.Code, 
   pc.BookingReference  
INTO #CodesToVoid
from J2H.dbo.Promotions p...

如果您使用Create Table方法,那么对于本地使用的表,“表变量”可能是比临时表更好的选择。即:

declare @CodesToVoid table
        (
        MasterPromoId int, 
        PromoId int, 
        Code nchar(10), 
        BookingReference nvarchar(50)   
        );

INSERT @CodesToVoid
SELECT p.PromotionId, pc.PromotionId, pc.Code, pc.BookingReference  
from J2H.dbo.Promotions p...