2014-02-11 74 views
0

我寫了一個像下面這樣的代碼插入一個逗號分隔值到tempTble.It正在工作,但我需要輸入的值的順序相同,因爲我正在將它傳遞給query.But這裏的數字是按數字順序排列和字符串值按照字母順序排列。例子'7,6,5,1,2,Jack,Ana,Micky',但是它按照'1,2,5,6,7,Ana,Jack ,米奇」。如何按照與傳遞順序相同的順序將逗號分隔值插入到SQL表中?

您能否爲此提供答案。 預先感謝您

ALTER PROCEDURE [dbo].[usp_GetValuesFromBillingSystem] 
(
@BillingSystemCode VARCHAR(max) 
) 
AS 
BEGIN 
DECLARE @planID varchar(max) = Null ; 

SET @planID= @BillingSystemCode 
DECLARE @tempTble Table (planID varchar(50) NULL); 
while len(@planID) > 0 
begin 
insert into @tempTble (planID) values(left(@planID , charindex(',', @planID +',')-1)) 
set @planID = stuff(@planID , 1, charindex(',', @planID +','), '') 
end 
select * from @tempTble 

END 

回答

0

www.aspdotnet-suresh.com/2013/07/sql-server-split-function-example-in.html

CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1)) 

RETURNS @Results TABLE (Items nvarchar(4000)) 

AS 

BEGIN 

DECLARE @INDEX INT 

DECLARE @SLICE nvarchar(4000) 

-- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z 
--  ERO FIRST TIME IN LOOP 

SELECT @INDEX = 1 

WHILE @INDEX !=0 

BEGIN 

-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER 

SELECT @INDEX = CHARINDEX(@Delimiter,@STRING) 

-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE 

IF @INDEX !=0 

SELECT @SLICE = LEFT(@STRING,@INDEX - 1) 

ELSE 

SELECT @SLICE = @STRING 

-- PUT THE ITEM INTO THE RESULTS SET 

INSERT INTO @Results(Items) VALUES(@SLICE) 

-- CHOP THE ITEM REMOVED OFF THE MAIN STRING 

SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX) 

-- BREAK OUT IF WE ARE DONE 

IF LEN(@STRING) = 0 BREAK 

END 

RETURN 

END 
相關問題