這段代碼解析由逗號的字符串,然後分割基於管道的位置,結果是:
SET NOCOUNT ON
DECLARE
@keyPair VARCHAR(1000),
@myEmpID VARCHAR(1000),
@myProductID VARCHAR(1000)
DECLARE @myKeyIDs VARCHAR(1000)
SET @myKeyIDs = '2232|33,4555|111,43343|65'
DECLARE
@len INT,
@pos INT,
@found INT
SELECT
@len = LEN(@myKeyIDs),
@pos = 1
SET @myKeyIDs = @myKeyIDs + ','
/* Find the first instance of a comma */
SET @found = CHARINDEX(',', @myKeyIDs, @pos)
WHILE @found > 0
BEGIN
/* The key pair starts at the @pos position and goes */
/* to the @found position minus the @pos position */
SET @keyPair= SUBSTRING(@myKeyIDs, @pos, @found - (@pos))
/* Double-check that pipe exists to avoid failure */
/* If no pipe exists, assume value is myEmpID */
IF CHARINDEX('|',@keyPair) = 0
BEGIN
SET @myEmpID = NULLIF(@keyPair, '')
SET @myProductID = NULL
END
ELSE
BEGIN
/* myEmpID is everything left of the pipe */
/* myProductID is everything on the right */
SET @myEmpID = NULLIF(SUBSTRING(@keyPair, 1,
CHARINDEX('|', @keyPair) - 1), '')
SET @myProductID = NULLIF(SUBSTRING(@keyPair,
CHARINDEX('|', @keyPair) + 1, LEN(@keyPair) - 1), '')
END
/*
INSERT EmployeeOrderLinkend(EmpId,OrderId,ProductId)
VALUES(@myEmpID,@OrderIdPassedAsParamInSP, @myProductId)
*/
SELECT @myEmpID AS myEmpID, @myProductID AS myProductID
/* Move to the next position and search again */
SET @pos = @found + 1
SET @found = CHARINDEX(',', @myKeyIDs, @pos)
END
一個與字符串解析試圖處理所有的邊緣情況的問題。您必須爲丟失逗號,丟失管道,過多管道,確認您的值是數字等等做好準備。如果可能,我們也遷移到使用表值參數...
來源
2010-07-08 04:54:22
8kb
感謝您的鏈接 你能告訴我你將如何使用它來提取我的2個單獨的values.As說每個鍵是由兩個值組成我需要提取。 感謝您的時間 – user9969 2010-07-07 21:09:14
嗨感謝您的例子非常grateful.As你說你可以做同樣的分裂function.I做了以下 CREATE TABLE #tmpKeys(setKeys VARCHAR(200)) \t \t \t INSERT INTO #tmpKeys(setKeys) \t \t從fnSplit選擇*(@MyKeyIds, '') \t \t \t \t SELECT * FROM #tmpKeys \t \t \t \t DROP TABLE #tmpKeys 以上將分割爲逗號。但現在我需要在|分割。 我該如何做到這一點,並填充我的行? 感謝您的任何輸入 – user9969 2010-07-08 05:20:04
您只需要做我已經擁有的只需使用@IDset作爲@MyKeyIds的位置並設置@Delimiter,或設置一個不同的變量,設置爲|代替 ,。猜測你將不得不把它放在某個地方。 – Kyra 2010-07-08 14:28:04