CREATE TYPE UserIdList AS TABLE(userId uniqueidentifier NOT NULL);
CREATE PROC insertIntoExamArrange@subjectId uniqueidentifier,@startTime datetime2(0),@duration time(7),@site nvarchar(255),@examName nvarchar(255),@studentIdList dbo.UserIdList READONLY,@supervisorIdList dbo.UserIdList READONLYASBEGINDECLARE @op TABLE (colGuid uniqueidentifier);DECLARE @examId uniqueidentifier;BEGIN TRANINSERT INTO dbo.ExamArrange(subjectId,startTime,duration,site,examName)OUTPUT inserted.examIdINTO @opVALUES(@subjectId, @startTime, @duration, @site, @examName);SELECT TOP 1@examId = colGuidFROM @op;INSERT INTO dbo.Exam_Student_Relationship(examId,studentId)SELECT @examId, userIdFROM @studentIdList;INSERT INTO dbo.Exam_Supervisor_Relationship(examId,supervisorId)SELECT @examId, userIdFROM @supervisorIdList;COMMITEND
DECLARE @studentList UserIdList;INSERT INTO @studentListVALUES(‘38C6D0B1-948D-412F-80BA-5BADDD7ABF53‘),(‘A3E7AAFF-3C0A-4B27-B92E-15DC5FA479BA‘);DECLARE @supervisorList UserIdList;INSERT INTO @supervisorListVALUES(‘DE6E2A5B-05D9-484A-B225-C8C7265A816B‘),(‘2EEBE00E-117D-4382-9828-93C7F6922F75‘);EXEC dbo.insertIntoExamArrange‘D5C544C2-9983-4805-8599-44DDE095289D‘,‘2015-12-18 18:16:30‘,‘1:50:33‘,‘测试楼‘,‘编译原理临时考试‘,@studentList,@supervisorList;
public void insertExamArrange(ExamArrange arr, List<User> supervisors,List<User> students) throws SQLException {StringBuilder query = new StringBuilder();if (students.size() > 0) {query.append(" DECLARE @studentList UserIdList; "+ " INSERT INTO @studentList VALUES(?) ");for (int i = 0; i < students.size() - 1; ++i) {query.append(" ,(?) ");}query.append(" ; ");}else{assert students.size()==0;query.append(" DECLARE @studentList UserIdList; ");}if (supervisors.size() > 0) {query.append(" DECLARE @supervisorList UserIdList; "+ " INSERT INTO @supervisorList VALUES(?) ");for (int i = 0; i < students.size() - 1; ++i) {query.append(" ,(?) ");}query.append(" ; ");}else{assert supervisors.size()==0;query.append(" DECLARE @supervisorList UserIdList; ");}query.append(" EXEC dbo.insertIntoExamArrange "+" ?,?,?,?,?,@studentList,@supervisorList; ");try(PreparedStatement pre = getConnection().prepareStatement(query.toString())){int preIndex = 1;for(int i=0;i<students.size();++i){pre.setString(preIndex, students.get(i).getUserId());++preIndex;}for(int i=0;i<supervisors.size();++i){pre.setString(preIndex, supervisors.get(i).getUserId());++preIndex;}pre.setString(preIndex,arr.getSubjectId());++preIndex;pre.setTimestamp(preIndex, arr.getStartTime());++preIndex;pre.setTime(preIndex, arr.getDuration());++preIndex;pre.setString(preIndex, arr.getSite());++preIndex;pre.setString(preIndex, arr.getExamName());++preIndex;pre.execute();}}
在JDBC中传递table参数给SQL server stored procedure
原文:http://www.cnblogs.com/cmicat/p/5080647.html