[英]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.当用户按下界面上的“拉”按钮从而将数据从一个服务器复制到另一台服务器时,将调用此 sp。
but now the issue is since we have a Course_Id
which is a foreign key from another master table ie Courses (Id, CourseName).
但现在的问题是因为我们有一个
Course_Id
,它是另一个主表的外键,即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
.现在一切都很好,因为所有数据都是相同的,因此来自Courses的主键在两个服务器上的两个表中都是相同的,但是如果
Courses
表中的记录是在源数据库中手动创建的,例如Id= 29
并且使用上面的查询从源到目标数据库然后它将在目标数据库的表(CoursesStudent)中有一个Course_Id
,它在目标数据库的Courses
表中不存在,因为我们没有同步主表,即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.现在,我的想法是创建一个用户定义的 function 即
CheckCourseAvailability
与CourseID
作为参数,将从源课程表中获取CourseName
并检查目标Courses
表,如果它不存在然后INSERT
并获取其Id
并返回在上面的查询中使用返回值作为 Course_ID。
Would this work if use like this如果像这样使用这会起作用吗
INSERT INTO CoursesStudent( [StudentName],[Course_Id] )插入课程学生([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注意:
CourseName
是唯一的
It's the wrong path.这是错误的道路。 You need to do two tasks:
你需要做两个任务:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.