六 29
我的工作, 数据库 split, SQL, 循环 No Comments
最近在做一个老系统的维护,数据库设计很牛B,没有主子表的关系表,主表中有一个字段用字符串“12;32;43”的形式保存子表主键ID。新的SR中我建了一个关系表,问题就来了,前台是通过字符串形式传过来子表的list,所以必须分开他们,然后一个个插到数据表中。
先用一个Split方法把字符串分开:
CREATE FUNCTION [dbo].[Split]
(
-- Add the parameters for the function here
@splitString VARCHAR(8000),
@separate VARCHAR(10)
)
RETURNS @returnTable TABLE(col_Value VARCHAR(20))
AS
BEGIN
DECLARE @thisSplitStr VARCHAR(20)
DECLARE @thisSepIndex INT
DECLARE @lastSepIndex INT
SET @lastSepIndex = 0
IF RIGHT(@splitString ,len(@separate)) <> @separate SET @splitString = @splitString + @separate
SET @thisSepIndex = CharIndex(@separate,@splitString ,@lastSepIndex)
while @lastSepIndex <= @thisSepIndex
BEGIN
SET @thisSplitStr = SUBSTRING(@splitString ,@lastSepIndex,@thisSepIndex-@lastSepIndex)
SET @lastSepIndex = @thisSepIndex + 1
SET @thisSepIndex = CharIndex(@separate,@splitString ,@lastSepIndex)
INSERT INTO @returnTable VALUES(@thisSplitStr)
END
RETURN
END
GO
(
-- Add the parameters for the function here
@splitString VARCHAR(8000),
@separate VARCHAR(10)
)
RETURNS @returnTable TABLE(col_Value VARCHAR(20))
AS
BEGIN
DECLARE @thisSplitStr VARCHAR(20)
DECLARE @thisSepIndex INT
DECLARE @lastSepIndex INT
SET @lastSepIndex = 0
IF RIGHT(@splitString ,len(@separate)) <> @separate SET @splitString = @splitString + @separate
SET @thisSepIndex = CharIndex(@separate,@splitString ,@lastSepIndex)
while @lastSepIndex <= @thisSepIndex
BEGIN
SET @thisSplitStr = SUBSTRING(@splitString ,@lastSepIndex,@thisSepIndex-@lastSepIndex)
SET @lastSepIndex = @thisSepIndex + 1
SET @thisSepIndex = CharIndex(@separate,@splitString ,@lastSepIndex)
INSERT INTO @returnTable VALUES(@thisSplitStr)
END
RETURN
END
GO
然后循环插入数据:
DECLARE @INDEX INT
SELECT @INDEX = 1
DECLARE @charNumber INT
DECLARE @chartID INT
SELECT IDENTITY(INT,1,1) indexID, col_Value INTO #tmp FROM Split('12;32;43',';')
SELECT @charNumber = COUNT(*) FROM #tmp
while(@INDEX <= @charNumber)
BEGIN
SELECT @chartID = col_Value FROM #tmp WHERE @INDEX = indexID
SELECT @chartID
SELECT @INDEX=@INDEX + 1
END
DROP TABLE #tmp
SELECT @INDEX = 1
DECLARE @charNumber INT
DECLARE @chartID INT
SELECT IDENTITY(INT,1,1) indexID, col_Value INTO #tmp FROM Split('12;32;43',';')
SELECT @charNumber = COUNT(*) FROM #tmp
while(@INDEX <= @charNumber)
BEGIN
SELECT @chartID = col_Value FROM #tmp WHERE @INDEX = indexID
SELECT @chartID
SELECT @INDEX=@INDEX + 1
END
DROP TABLE #tmp
把上边的第11行换成insert语句即可!
RSS
Twitter
Facebook
Google+
eMail
近期评论