简体   繁体   中英

How to insert row for each unique value found in column

How could I, in SQL Server 2008, write a SQL statement that would insert one row for each distinct value it finds in one column in the same table?

Edit:
The table I want to add rows to the same table I'm checking.

I have normalized table with a column [Name], and [Hobby], so how do I insert one new hobby for each name?

Input greatly appreciated =]

try

INSERT INTO TargetTable (SomeColumn)
SELECT DISTINCT TheSourceColumn From SomeSourceTable;

IF that is not what you are looking for please provide more details like what the data model looks like etc.

UPDATE - after edit from OP:

I am not sure that you data model is good but you can do this:

INSERT INTO TheTable (NAME, HOBBY)
SELECT DISTINCT X.NAME, @SomeHOBBY FROM TheTable X;

You could use something like

Insert into table1
Select distinct col1 from tabl2

The above should work as long as table1 has just one column of the same data type as col1 of tabl2

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