简体   繁体   中英

Insert values from a different table with a new column with constant value in T-SQL

I am inserting all values from a table into another table, which is created on the fly. I want to insert one extra column with constant value to the new table I create.

I have my FinSls table like this,

Time             Terminal_ID   Count
------------------------------------
2017-10-19 06:03:00     1       5
2017-10-19 06:04:00     1       2
2017-10-19 06:05:00     1       2
2017-10-19 06:06:00     1       2
2017-10-19 06:03:00     9       2
2017-10-19 06:04:00     9       3
2017-10-19 06:05:00     9       2
2017-10-19 06:06:00     9       3

I am creating a new table BinTable and I want to add a column cons_val with a constant value, for example: 1, like this,

Time              Terminal_ID  Count  Cons_value
------------------------------------------------
2017-10-19 06:03:00     1       5      1
2017-10-19 06:04:00     1       2      1
2017-10-19 06:05:00     1       2      1
2017-10-19 06:06:00     1       2      1
2017-10-19 06:03:00     9       2      1
2017-10-19 06:04:00     9       3      1
2017-10-19 06:05:00     9       2      1
2017-10-19 06:06:00     9       3      1

So far I have my script like this,

select *
into  
   BinTable
from 
   FinlSls

How can I add a new column Cons_Value into my BinTable ? I saw this post that already has the table created and then inserting value. But in my situation, how can I do this?

Any help would be awesome.

You just add it:

select f.*, 1 as cons_value
into BinTable
from FinlSls f;

There may be some criticism in using select * instead of listing out the columns.

You can treat it like any other INSERT statement and choose which columns are inserted into. In addition, you can choose which columns are selected, which allows you to joins as well.

It's good to define the table first, to ensure you create primary keys etc, I thought this was already being created as part of your process. I'm assuming this is a one time deal, in which case you would want tables indexed properly. If this was a temporary table for use in a stored procedure, then I would suggest using a temporary table (begins with a #).

CREATE TABLE
   [BinTable]
(
   [BinTableID] INT PRIMARY KEY IDENTITY(1,1),
   [Time] DATETIME,
   [Terminal_ID] INT,
   [Count] INT,
   [Cons_val] INT
);

Then you can insert the data.

INSERT INTO
   [BinTable]
([Time], [Terminal_ID], [Count], [Cons_value])
SELECT
    [Time], 
    [Terminal_ID], 
    [Count],
    1 AS [Cons_value]
FROM
    [FinSls];

If the new table already exists, use INSERT SELECT, else you can use the code below

SELECT Time, Terminal_ID, Count, 1
INTO BinTable
FROM FinlSls

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM