我的SQL代码中已经有了这么多。我很难根据奇数和偶数将我的数据打印在两个单独的表中。提前感谢您的意见。我真的很感激。
DECLARE
@empNM CHAR(15),
@empID INT,
@reportsTO INT
DECLARE
emp CURSOR dynamic FOR
SELECT Employee_NM, Employee_ID, ReportsTo
FROM employeetable
ORDER BY Employee_ID ASC
OPEN emp
FETCH NEXT
FROM emp
INTO @empNM, @empID, @reportsTO;
PRINT 'name id boss'
WHILE (@@fetch_status <> -1)
IF (@empID % 2 = 0)
BEGIN
SET @empNM = CONVERT(CHAR,CAST(@empNM AS VARCHAR),1)
PRINT CAST(@empNM AS VARCHAR)+CAST(@empID AS VARCHAR)+SPACE(11)+CAST(@reportsTO AS varCHAR)
FETCH NEXT
FROM emp
INTO @empNM, @empID, @reportsTO;
END;
ELSE
BEGIN
SET @empNM = CONVERT(CHAR,CAST(@empNM AS VARCHAR),1)
PRINT CAST(@empNM AS VARCHAR)+CAST(@empID AS VARCHAR)+SPACE(11)+CAST(@reportsTO AS varCHAR)
FETCH NEXT
FROM emp
INTO @empNM, @empID, @reportsTO;
END;
CLOSE emp;
DEALLOCATE emp;
这是理想的结果......
答案 0 :(得分:1)
您没有使用C#循环数据。使用SQL,您必须处理整个数据集,因此没有游标。 (在大多数情况下)
您必须为每个表执行1次插入:
Insert Into TOdd(Name, Id, Boss) Select Name, Id, Boss From T Where id % 2 = 1
Insert Into TEven(Name, Id, Boss) Select Name, Id, Boss From T Where id % 2 = 0
请参阅SQL小提琴:http://sqlfiddle.com/#!3/212a9/1/0