简体   繁体   中英

Using a user-defined function in select statement on a column in conjunction with INSERT

INSERT INTO CoursesStudent(
                    [StudentName]
                       ,[Course_Id]
                    )

                SELECT [StudentName]
                       ,[Course_Id]
                FROM [192.xxx.xxx.xxx].studentsDb.dbo.CoursesStudent
                WHERE [Id] = @Id

I am trying to insert all the matching data from table to table which are same but on different db servers. It works since

This sp is called when a user press a 'pull' button on the interface hence copying data from one to another server.

but now the issue is since we have a Course_Id which is a foreign key from another master table ie Courses (Id, CourseName).

Now all is good since all the data is same hence Primary key from Courses are same in both tables on both servers but if a record in Courses table is created manually in source db eg with Id= 29 and the data copied using the query above from source to target db then it will have a Course_Id in target db's table (CoursesStudent) which doesn't exist in the Courses table on target db since we are not syncing the master tables ie Courses .

Now, my idea is to create a USER-DEFINED function ie CheckCourseAvailability with CourseID as a param that would fetch the CourseName from Source Course table and check in the target Courses table if it doesn't exist then INSERT and get its Id and return hence using the return value as a Course_ID in the query above.

Would this work if use like this

INSERT INTO CoursesStudent( [StudentName],[Course_Id] )

            SELECT [StudentName]
                   ,CheckCourseAvailability([Course_Id])
            FROM [192.xxx.xxx.xxx].studentsDb.dbo.CoursesStudent
            WHERE [Id] = @Id

would it be ok? Or do you have any other better idea?

Note: CourseName is unique

It's the wrong path. You need to do two tasks:

  1. Synchronise your Courses tables.

eg

INSERT INTO Courses (Id, CourseName)
SELECT [Id],[CourseName]
FROM [192.xxx.xxx.xxx].studentsDb.dbo.Courses
WHERE NOT EXISTS (SELECT TOP(1) Id FROM your_primary_db.dbo.Courses.id = [192.xxx.xxx.xxx].studentsDb.dbo.Courses.Id)
  1. Insert new records to Course Student after that.

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