简体   繁体   中英

Copying row to another one in SQL Server from Asp.NET

Assume that there is a table which includes only ID, Name, Company and RealID .

I want to copy one row to another one. For ex:

ID          Name           Company         RealID

1          Marry           Company A        null
2          Jane            Company B        null
3          Watson          Company C        null
4          Marry           Company A         1
5          Watson          Company C         3

I will do this from asp.net via c# programming language.

My question is:

In c# should I do below?

Class: UserProfile {ID, Name, Company, RealID}

Code side:

UserProfile userProfile = new UserProfile();
//I have userProfile.ID, userProfile.Name, userProfile.Company and userProfile.RealID
SqlConnection conn = new SqlConnection(sqlConnection);
SqlCommand cmd = new SqlCommand("Select * From UserProfile", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);

//and with a loop, assignment to UserProfile members such as UserProfile.ID = dr[0][i]...

and after that SQL query will be

INSERT (Name, Company, RealID) 
VALUES (UserProfile.Name, UserProfile.Company, UserProfile.RealID)

I search this subject and find this: Copying values from another row

but I think my case is different.

Or are there any method to shorten this process?

Shortly:

I want to copy one row to another one in sql from asp.net.

Thanks for help

Looks like you pretty much have all the code, so why you need a shortcut? I don't know of a shortcut, and if the data is as trivial as your example, who cares! Just read it out and write it...

我不确定我是否正确理解了这个问题,但是如果您想将一个表中的行逐行复制到另一张表中,可以使用INSERT INTO,

If this is just a copy of one row and Id is auto-incrementing, perhaps you could do this as SQL only?

INSERT INTO UserProfile (Name, Company, RealID) SELECT Name, Company, RealID FROM UserProfile WHERE ID = X

You could also substitute if there are select changed values:

INSERT INTO UserProfile (Name, Company, RealID) SELECT 'New Name', Company, RealID FROM UserProfile WHERE ID = X

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