我正在使用MSSQL。下面是我的sql代码
DECLARE @CoursesAboutToExpire TABLE (CourseID BIGINT, ExpiryDate DATE, IsApplicableToAllInternalUser BIT)
INSERT INTO @CoursesAboutToExpire
SELECT CourseID, ExpiryDate, IsApplicableToAllInternalUser
FROM CMS_CoursesMaster CM
DECLARE @ApplicableUsersWithCourse TABLE (UserID BIGINT, CourseID BIGINT)
SELECT 1 ,
(CASE WHEN CAE.IsApplicableToAllInternalUser = 1
THEN (INSERT INTO @ApplicableUsersWithCourse SELECT UM.UserID, CAE.CourseID FROM TRC_UserMaster UM)
ELSE (INSERT INTO @ApplicableUsersWithCourse SELECT CAP.UserID, CAP.CourseID FROM CMS_CourseApplicabilityParameters CAP WHERE CAP.CourseID=CAE.CourseID)
) AS 2
FROM @CoursesAboutToExpire CAE
我尝试使用case
语句在* IsApplicableToAllInternalUser *列值的基础上插入记录。但它给出了错误。
答案 0 :(得分:0)
现在您可以使用以下INSERT INTO .. SELECT
语句替换您尝试执行的CASE语句:
DECLARE @ApplicableUsersWithCourse TABLE (UserID BIGINT, CourseID BIGINT)
INSERT INTO @ApplicableUsersWithCourse
SELECT UM.UserID, CAE.CourseID
FROM TRC_UserMaster UM JOIN @CoursesAboutToExpire CAE ON UM.CourseID = CAE.CourseID
WHERE CAE.IsApplicableToAllInternalUser = 1
INSERT INTO @ApplicableUsersWithCourse
SELECT CAP.UserID, CAP.CourseID
FROM CMS_CourseApplicabilityParameters CAP JOIN @CoursesAboutToExpire CAE ON CAP.CourseID=CAE.CourseID
WHERE CAE.IsApplicableToAllInternalUser = 0
您可以通过首先执行SELECT
语句来初始测试要插入的记录。如果看起来没问题,可以插入记录。
这也可以写成如下:
INSERT INTO @ApplicableUsersWithCourse
SELECT UM.UserID, CAE.CourseID
FROM TRC_UserMaster UM JOIN @CoursesAboutToExpire CAE ON UM.CourseID = CAE.CourseID
WHERE CAE.IsApplicableToAllInternalUser = 1
UNION ALL
SELECT CAP.UserID, CAP.CourseID
FROM CMS_CourseApplicabilityParameters CAP JOIN @CoursesAboutToExpire CAE ON CAP.CourseID=CAE.CourseID
WHERE CAE.IsApplicableToAllInternalUser = 0
答案 1 :(得分:0)
下面的代码对我有用。
DECLARE @CoursesAboutToExpire TABLE (CourseID BIGINT, ExpiryDate DATE, IsApplicableToAllInternalUser BIT)
INSERT INTO @CoursesAboutToExpire
SELECT CourseID, ExpiryDate, IsApplicableToAllInternalUser FROM CMS_CoursesMaster CM
DECLARE @ApplicableUsersWithCourse TABLE (UserID BIGINT, CourseID BIGINT)
INSERT INTO @ApplicableUsersWithCourse
SELECT UM.UserID, CAE.CourseID FROM TRC_UserMaster UM
CROSS JOIN @CoursesAboutToExpire CAE
WHERE CAE.IsApplicableToAllInternalUser = 1)
INSERT INTO @ApplicableUsersWithCourse
SELECT CAP.UserID, CAP.CourseID FROM CMS_CourseApplicabilityParameters CAP
INNER JOIN @CoursesAboutToExpire CAE ON CAP.CourseID=CAE.CourseID
WHERE CAE.IsApplicableToAllInternalUser = 0