当前位置: 代码迷 >> Sql Server >> 关于存储过程的1点疑问
  详细解决方案

关于存储过程的1点疑问

热度:45   发布时间:2016-04-27 11:36:07.0
关于存储过程的一点疑问
SQL code
这个存储过程是将用户传入进来的字符串分开插入到数据库里面,语句如下:usp_Insert '0129100001,0129100002,0129100003,0129100004,0129100005,','C00001','LINE3','admin'目地是将0129100001,0129100002,0129100003,0129100004,0129100005分开插入到表里面,第一次插入的时候没有问题,但是如果数据库里面有重复的记录的话这个存储过程就变成死循环了,不知道是不是跟那个循环变量赋值的时候有问题呢?IF EXISTS(SELECT * FROM SYSOBJECTS WHERE name='usp_Insert')DROP PROC usp_InsertGOCREATE PROCEDURE usp_Insert    @SN VARCHAR(1024)=' ',    @CartonSN VARCHAR(20)=' ',    @LineName VARCHAR(5)=' ',    @UserID VARCHAR(10)=' 'AS--usp_Insert '0129100001,0129100002,0129100003,0129100004,0129100005,','C00001','LINE3','admin'  /*这一部分就是处理之后的SQL语句,INSERT INTO TestTB(SN,CartonSN,LineName,UserID,CreateDate) VALUES('0129100001','C00001','LINE3','admin',GETDATE()) INSERT INTO TestTB(SN,CartonSN,LineName,UserID,CreateDate) VALUES('0129100002','C00001','LINE3','admin',GETDATE())  INSERT INTO TestTB(SN,CartonSN,LineName,UserID,CreateDate) VALUES('0129100003','C00001','LINE3','admin',GETDATE())   INSERT INTO TestTB(SN,CartonSN,LineName,UserID,CreateDate) VALUES('0129100004','C00001','LINE3','admin',GETDATE())      INSERT INTO TestTB(SN,CartonSN,LineName,UserID,CreateDate) VALUES('0129100005','C00001','LINE3','admin',GETDATE())*/BEGIN TRANDECLARE @SN_N VARCHAR(1024),@ERRDESC VARCHAR(100)SELECT @SN_N [email protected]WHILE CHARINDEX(',',@SN_N)>0BEGIN     IF NOT EXISTS(SELECT * FROM PK2 WHERE SN=LEFT(@SN_N,CHARINDEX(',',@SN_N)-1))        BEGIN                INSERT INTO TestTB(SN,CartonSN,LineName,UserID,CreateDate)             VALUES(LEFT(@SN_N,CHARINDEX(',',@SN_N)-1),@CartonSN, @LineName,@UserID,GETDATE())           SET @SN_N=REPLACE(@SN_N,LEFT(@SN_N,CHARINDEX(',',@SN_N)),'')            IF @@ERROR<>0        BEGIN            SELECT  FERRDESC='数据保存失败'            RAISERROR(@ERRDESC,16,1)            ROLLBACK TRAN            RETURN        END    ENDENDCOMMIT TRAN


------解决方案--------------------
先SF,慢慢看
------解决方案--------------------
SQL code
 IF NOT EXISTS(SELECT * FROM PK2 WHERE SN=LEFT(@SN_N,CHARINDEX(',',@SN_N)-1))        BEGIN                INSERT INTO TestTB(SN,CartonSN,LineName,UserID,CreateDate)             VALUES(LEFT(@SN_N,CHARINDEX(',',@SN_N)-1),@CartonSN, @LineName,@UserID,GETDATE())           SET @SN_N=REPLACE(@SN_N,LEFT(@SN_N,CHARINDEX(',',@SN_N)),'')            IF @@ERROR<>0        BEGIN            SELECT  FERRDESC='数据保存失败'            RAISERROR(@ERRDESC,16,1)            ROLLBACK TRAN            RETURN        END    ENDelse SET @SN_N=REPLACE(@SN_N,LEFT(@SN_N,CHARINDEX(',',@SN_N)),'')  --加这句就可以了
  相关解决方案