Need help finding error in stored procedure - sql-server
I cant seem to get the stored procedure code to execute without errors such as:
Msg 156, Level 15, State 1, Procedure task5proc, Line 37 [Batch Start Line 37]
Incorrect syntax near the keyword 'and'.
Msg 156, Level 15, State 1, Procedure task5proc, Line 40 [Batch Start Line 37]
Incorrect syntax near the keyword 'else'.
Msg 102, Level 15, State 31, Procedure task5proc, Line 71 [Batch Start Line 37]
Incorrect syntax near '('
Code from here:
create table dbo.task5
(
id int identity,
col1 varchar(10),
col2 varchar(10),
col3 varchar(10),
col4 varchar(10),
maincolumn varchar(50)
)
insert into task5
values (null, null, null, null, '1-AS,2-34,3-DF,4-fG'),
(null, null, null, null, '3-AS,4-fG'),
(null, null, null, null, '1-sd,3-df,4-ds'),
(null, null, null, null, '1-25,2-ww,3-d,4-ss'),
(null, null, null, null, '1-sd,2-AS,4-fG')
select * from dbo.task5
go
create or alter proc dbo.task5proc (#maxcount int)
as
begin
declare #counter int, #var varchar(50)
set #counter = 1
set #var = (select maincolumn from dbo.task5 where id = #counter)
declare #give1 varchar(10), #give2 varchar(10), #give3 varchar(10), #give4 varchar(10)
while #counter <= #maxcount
begin
begin
if charindex('1-', #var , 1) = 0
set #give1 = 'N/P'
else
set #give1 = SUBSTRING(#var , charindex('1-', #var , 1)+2, charindex(',', #var , 1)-3)
end
begin
if (charindex('2-', #var , 1)) !=0 and charindex('1-', #var , 1) != 0
set #give2 = substring(#var, (charindex('2-', #var , 1)+2), (charindex(',', #var, charindex(',', #var,1)+1))-(charindex('2-', #var , 1)+2))
else if (charindex('2-', #var , 1)) !=0 and charindex('1-', #var , 1) = 0
set #give2 = SUBSTRING(#var , charindex('2-', #var , 1)+2, charindex(',', #var , 1)-3)
else
set #give2 = 'N/P'
end
begin
if (charindex('3-', #var,1)) != 0 and (charindex('2-', #var , 1)) !=0 and charindex('1-', #var , 1) != 0
set #give3 = substring(#var, (charindex('3-', #var,1)+2), charindex(',', #var,charindex(',', #var,(charindex(',',#var,1) +1)) +1) - (charindex('3-', #var,1)+2))
else if (charindex('3-', #var,1)) != 0 and (charindex('2-', #var , 1)) !=0 and charindex('1-', #var , 1) = 0
set #give3 = substring(#var, (charindex('3-', #var , 1)+2), (charindex(',', #var, charindex(',', #var,1)+1))-(charindex('2-', #var , 1)+2))
else if (charindex('3-', #var,1)) != 0 and (charindex('1-', #var , 1)) !=0 and and charindex('2-', #var , 1) = 0
set #give3 = substring(#var, (charindex('3-', #var , 1)+2), (charindex(',', #var, charindex(',', #var,1)+1))-(charindex('1-', #var , 1)+2))
else
set #give3 = 'N/P'
end
begin
if (charindex('4-', #var,1)) != 0 and (charindex('3-', #var,1)) != 0 and (charindex('2-', #var , 1)) !=0 and charindex('1-', #var , 1) != 0
set #give4 = right(#var, (charindex('4-', #var, 1) + 2) - charindex(',', #var,charindex(',', #var,(charindex(',',#var,1) +1)) +1))
else if (charindex('4-', #var,1)) != 0 and (charindex('3-', #var , 1)) = 0 and charindex('2-', #var , 1) != 0 and charindex('1-', #var , 1) != 0
set #give4 = right(#var, (charindex('4-', #var, 1) + 2) - charindex(',', #var,(charindex(',',#var,1) +1)))
else if (charindex('4-', #var,1)) != 0 and (charindex('2-', #var , 1)) =0 and charindex('1-', #var , 1) != 0 and charindex('3-', #var , 1) != 0
set #give4 = right(#var, (charindex('4-', #var, 1) + 2) - charindex(',', #var,(charindex(',',#var,1) +1)))
else if (charindex('4-', #var,1)) != 0 and (charindex('2-', #var , 1)) !=0 and charindex('1-', #var , 1) = 0 and charindex('3-', #var , 1) != 0
set #give4 = right(#var, (charindex('4-', #var, 1) + 2) - charindex(',', #var,(charindex(',',#var,1) +1)))
else if (charindex('4-', #var,1)) != 0 and (charindex('3-', #var , 1)) !=0 and charindex('2-', #var , 1) = 0 and charindex('1-', #var , 1) = 0
set #give4 = right(#var, (charindex('4-', #var, 1) + 2) - (charindex(',',#var,1) +1))
else if (charindex('4-', #var,1)) != 0 and (charindex('3-', #var , 1)) =0 and charindex('2-', #var , 1) != 0 and charindex('1-', #var , 1) = 0
set #give4 = right(#var, (charindex('4-', #var, 1) + 2) - (charindex(',',#var,1) +1))
else if (charindex('4-', #var,1)) != 0 and (charindex('3-', #var , 1)) =0 and charindex('2-', #var , 1) = 0 and charindex('1-', #var , 1) != 0
set #give4 = right(#var, (charindex('4-', #var, 1) + 2) - (charindex(',',#var,1) +1))
else
set #give4= 'N/P'
end
update task5(col1, col2, col3, col4)
set col1 = #give1, col2 = #give2, col3 = #give3, col4 = #give4
where id = #counter
set #counter = #counter + 1
set #var = (select maincolumn from dbo.task5 where id = #counter)
end
end
go
exec task5proc(select count(*) from dbo.task5)
Don't you have any intelliSense?
On row 57 you have a double and:
else if (charindex('3-', #var,1)) != 0
and (charindex('1-', #var , 1)) !=0
and and /*<--- THIS WONT WORK*/ charindex('2-', #var , 1) = 0
set #give3 = substring(#var, (charindex('3-', #var , 1)+2), (charindex(',', #var, charindex(',', #var,1)+1))-(charindex('1-', #var , 1)+2))
Related
Error "Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements" after execute the stored procedure
I'm getting the error on the title when trying to execute the stored procedure "{"Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0.\r\nTransaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0."}" SET ansi_nulls ON go SET quoted_identifier ON go ALTER PROCEDURE [dbo].[Updatepayments] #FileBank VARCHAR(max), #CreatedBy INT, #RequestPayment VARCHAR(max) out AS BEGIN BEGIN try SET nocount ON; SET XACT_ABORT ON; BEGIN TRANSACTION SET #RequestPayment = ''; DECLARE #line VARCHAR(max), #RequestId INT, #PaymentId BIGINT, #companyCode VARCHAR(max), #bankCode VARCHAR(max), #Date VARCHAR(max), #sumAmount VARCHAR(max), #recordCount VARCHAR(max), #bankBranchCode VARCHAR(max), #ChanalCode VARCHAR(max), #PaymentDate VARCHAR(max), #billNumber VARCHAR(max), #paymentNumber VARCHAR(max), #TrackNumber VARCHAR(max), #PaymentExtra VARCHAR(max), #Amount VARCHAR(max), #CurrentStageId INT, #NextStageId INT, #ErrorMsg VARCHAR(max), #ErrorNumber INT, #ErrorProc SYSNAME, #ErrorLine INT; DECLARE req_cursor CURSOR FOR SELECT * FROM Splitstring(#FileBank, Char(10)); OPEN req_cursor; FETCH next FROM req_cursor INTO #line SET #companyCode=Substring(#FileBank, 1, 4); SET #bankCode=Substring(#FileBank, 5, 2); SET #Date=Substring(#FileBank, 7, 6); SET #sumAmount=Substring(#FileBank, 13, 16); SET #recordCount=Substring(#FileBank, 29, 8); SET #Amount = 0; FETCH next FROM req_cursor INTO #line WHILE ##FETCH_STATUS = 0 BEGIN SET #bankBranchCode=Substring(#line, 1, 6); SET #ChanalCode=Substring(#line, 7, 2) SET #PaymentDate=( CASE WHEN Cast(Substring(#line, 9, 2) AS INT) < 99 THEN '14' + Substring(#line, 9, 6) ELSE '13' + Substring(#line, 9, 6) END ); SET #billNumber =Cast(Cast(Substring(#line, 15, 18) AS BIGINT)AS VARCHAR(max)); SET #paymentNumber=Cast(Cast(Substring(#line, 33, 18) AS BIGINT) AS VARCHAR ( max)); SET #TrackNumber=Substring(#line, 51, 6); SET #PaymentExtra=Substring(#line, 57, 13); SET #Amount = 0; IF EXISTS (SELECT 1 FROM [dbo].[bankaccountinfo] WHERE companycode = #companyCode) IF EXISTS(SELECT 1 FROM [dbo].[payment] WHERE billnumber = #billNumber AND paymentnumber = #paymentNumber) BEGIN SELECT #RequestId = requestid, #PaymentId = paymentid, #Amount = Cast(Cast(amount AS BIGINT)AS VARCHAR(max)) FROM payment WHERE billnumber = #billNumber AND paymentnumber = #paymentNumber; SELECT #CurrentStageId = lastexecutedstageid FROM vrequest WHERE requestid = #RequestId; -- Fix empty values to null in order to set the null to 0 SET #billNumber = CASE WHEN #billNumber = '' THEN NULL ELSE #billNumber END SET #paymentNumber = CASE WHEN #paymentNumber = '' THEN NULL ELSE #paymentNumber END SET #Amount = CASE WHEN #Amount = '' THEN NULL ELSE #Amount END SET #bankBranchCode = CASE WHEN #bankBranchCode = '' THEN NULL ELSE #bankBranchCode END SET #TrackNumber = CASE WHEN #TrackNumber = '' THEN NULL ELSE #TrackNumber END SET #ChanalCode = CASE WHEN #ChanalCode = '' THEN NULL ELSE #ChanalCode END SET #RequestPayment = #RequestPayment + ( CASE WHEN #RequestPayment = '' THEN '' ELSE ',' END ) + ( CASE WHEN EXISTS(SELECT 1 FROM payment WHERE paymentid = #PaymentId AND ispaid = 0) THEN '1' ELSE '2' END ) + '|' + Isnull ( #billNumber, 0) + '|' + Isnull( #paymentNumber, 0 ) + '|' + Isnull(#Amount, 0) + '|' + ( Isnull(#bankBranchCode, 0) ) + '|' + ( Isnull( #TrackNumber, 0) ) + '|' + ( Isnull(#ChanalCode, 0) ); UPDATE [dbo].[payment] SET [ispaid] = 1, [paymentdate] = Cast(dbo.S2m(#PaymentDate) AS DATETIME) , [retrivalrefrencenumber] = #TrackNumber WHERE paymentid = #PaymentId AND ispaid = 0; SET #NextStageId = ( CASE #CurrentStageId WHEN 8 THEN 700 WHEN 1 THEN 2 WHEN 25 THEN 2 ELSE 0 END ); IF ( #NextStageId = 1 OR #NextStageId = 25 ) BEGIN EXECUTE [dbo].[Addrequestexecutestage] #RequestId, 2, 1, 'دریافت سیستمی اطلاعات پرداخت' END END ELSE BEGIN SET #RequestPayment = #RequestPayment + ( CASE WHEN #RequestPayment = '' THEN '' ELSE ',' END ) + '3|' + Isnull(#billNumber, 0) + '|' + Isnull( #paymentNumber, 0) + '|' + Isnull( #Amount, 0) + '|' + ( Isnull( #bankBranchCode , 0) ) + '|' + ( Isnull( #TrackNumber, 0 ) ) + '|' + ( Isnull(#ChanalCode, 0) ); END FETCH next FROM req_cursor INTO #line; END CLOSE req_cursor; DEALLOCATE req_cursor; COMMIT END try BEGIN catch SELECT #ErrorMsg = Error_message(), #ErrorNumber = Error_number(), #ErrorProc = Error_procedure(), #ErrorLine = Error_line(); ROLLBACK TRAN; INSERT INTO [dbo].[errorlog] (errormsg, errornumber, errorproc, errorline) VALUES (#ErrorMsg, #ErrorNumber, #ErrorProc, #ErrorLine) END catch END
Multi identifier error in trigger function
I have a trigger function that create for inserted. I have two stockTransaction and StokItem in the code I wanted to display the changes on StockItem and I succeeded it. But now I simply change the column BuyinPrice of my Item table which is third table after updating StokItem table. Here is my code: ALTER TRIGGER [dbo].[StockTransactionInserted] ON [dbo].[StockTransaction] AFTER INSERT AS BEGIN SET NOCOUNT ON; DECLARE #IdItem int, #IdStorage int, #TransactionType char(1), #Code char(1), #Quantity decimal(18, 8), #UnitPrice decimal(18, 8), #Discount decimal(18, 8), #FatAltDiscount decimal(18, 8), #VAT decimal(18, 8) SELECT #IdItem = IdItem, #IdStorage = IdStorage, #TransactionType = TransactionType, #Code = Code, #Quantity = Quantity, #UnitPrice = UnitPrice, #Discount = Discount, #FatAltDiscount = FatAltDiscount, #VAT = VAT FROM inserted IF NOT EXISTS (SELECT * FROM StockItem WHERE IdItem = #IdItem AND IdStorage = #IdStorage) BEGIN INSERT INTO StockItem (IdItem, IdStorage, TOP_GIRIS_MIK, TOP_CIKIS_MIK) VALUES (#IdItem, #IdStorage, 0, 0) END UPDATE StockItem SET TOP_GIRIS_MIK = TOP_GIRIS_MIK + CASE WHEN #Code = 'G' THEN #Quantity ELSE 0 END, TOP_GIRIS_TUT = TOP_GIRIS_TUT + CASE WHEN #Code = 'G' THEN (#UnitPrice * (1- #Discount/100)) * #Quantity ELSE 0 END, TOP_CIKIS_MIK = TOP_CIKIS_MIK + CASE WHEN #Code = 'C' THEN #Quantity ELSE 0 END, TOP_CIKIS_TUT = TOP_CIKIS_TUT + CASE WHEN #Code = 'C' THEN (#UnitPrice * (1- #Discount/100)) * #Quantity ELSE 0 END, ORT_BR_FIAT = CASE WHEN ((TOP_GIRIS_MIK - TOP_CIKIS_MIK) + #Quantity) = 0 THEN (ORT_BR_FIAT + (#UnitPrice * (1- #Discount/100))) / 2 ELSE ((TOP_GIRIS_MIK - TOP_CIKIS_MIK) * ORT_BR_FIAT + (#Quantity * (#UnitPrice * (1- #Discount/100)))) / ((TOP_GIRIS_MIK - TOP_CIKIS_MIK) + #Quantity) END, SON_GIR_BR_FIAT = (CASE WHEN #UnitPrice=0 OR #TransactionType != 'A' THEN SON_GIR_BR_FIAT ELSE #UnitPrice * (1- #Discount/100) END), SON_GIR_NET_FIAT = (CASE WHEN #UnitPrice=0 OR #TransactionType != 'A' THEN SON_GIR_NET_FIAT ELSE (#UnitPrice * (1- #Discount/100)) + (#UnitPrice * #VAT/100) END) WHERE IdItem = #IdItem AND IdStorage = #IdStorage UPDATE Item SET BuyingPrice = StockItem.SON_GIR_BR_FIAT where item_id = #IdItem END Actually Update StokItem is working it is not problem but when i want to update my Item table in here UPDATE Item SET BuyingPrice = StockItem.SON_GIR_BR_FIAT where item_id = #IdItem It says Multi identifier error for StockItem.SON_GIR_BR_FIAT column. Can you please help me! Thanks!
Now, it should work! The table Inserted can contain 0, 1 or multiple rows. So, you need to use a CURSOR with the rows affected in order to UPDATE the table StockItem and Item row by row. ALTER TRIGGER [dbo].[StockTransactionInserted] ON [dbo].[StockTransaction] AFTER INSERT AS BEGIN SET NOCOUNT ON; DECLARE #IdItem int, #IdStorage int, #TransactionType char(1), #Code char(1), #Quantity decimal(18, 8), #UnitPrice decimal(18, 8), #Discount decimal(18, 8), #FatAltDiscount decimal(18, 8), #VAT decimal(18, 8) DECLARE curStockTransaction CURSOR FOR SELECT IdItem, IdStorage, TransactionType, Code, Quantity, UnitPrice, Discount, FatAltDiscount, VAT FROM inserted OPEN curStockTransaction FETCH NEXT FROM curStockTransaction INTO #IdItem, #IdStorage, #TransactionType, #Code, #Quantity, #UnitPrice, #Discount, #FatAltDiscount, #VAT WHILE ##FETCH_STATUS = 0 BEGIN IF NOT EXISTS (SELECT * FROM StockItem WHERE IdItem = #IdItem AND IdStorage = #IdStorage) BEGIN INSERT INTO StockItem (IdItem, IdStorage, TOP_GIRIS_MIK, TOP_CIKIS_MIK) VALUES (#IdItem, #IdStorage, 0, 0) END UPDATE StockItem SET TOP_GIRIS_MIK = TOP_GIRIS_MIK + CASE WHEN #Code = 'G' THEN #Quantity ELSE 0 END, TOP_GIRIS_TUT = TOP_GIRIS_TUT + CASE WHEN #Code = 'G' THEN (#UnitPrice * (1- #Discount/100)) * #Quantity ELSE 0 END, TOP_CIKIS_MIK = TOP_CIKIS_MIK + CASE WHEN #Code = 'C' THEN #Quantity ELSE 0 END, TOP_CIKIS_TUT = TOP_CIKIS_TUT + CASE WHEN #Code = 'C' THEN (#UnitPrice * (1- #Discount/100)) * #Quantity ELSE 0 END, ORT_BR_FIAT = CASE WHEN ((TOP_GIRIS_MIK - TOP_CIKIS_MIK) + #Quantity) = 0 THEN (ORT_BR_FIAT + (#UnitPrice * (1- #Discount/100))) / 2 ELSE ((TOP_GIRIS_MIK - TOP_CIKIS_MIK) * ORT_BR_FIAT + (#Quantity * (#UnitPrice * (1- #Discount/100)))) / ((TOP_GIRIS_MIK - TOP_CIKIS_MIK) + #Quantity) END, SON_GIR_BR_FIAT = (CASE WHEN #UnitPrice=0 OR #TransactionType != 'A' THEN SON_GIR_BR_FIAT ELSE #UnitPrice * (1- #Discount/100) END), SON_GIR_NET_FIAT = (CASE WHEN #UnitPrice=0 OR #TransactionType != 'A' THEN SON_GIR_NET_FIAT ELSE (#UnitPrice * (1- #Discount/100)) + (#UnitPrice * #VAT/100) END) WHERE IdItem = #IdItem AND IdStorage = #IdStorage UPDATE Item SET BuyingPrice = StockItem.SON_GIR_BR_FIAT FROM Item JOIN StockItem ON (StockItem.IdItem = Item.item_id) where item_id = #IdItem FETCH NEXT FROM curStockTransaction INTO #IdItem, #IdStorage, #TransactionType, #Code, #Quantity, #UnitPrice, #Discount, #FatAltDiscount, #VAT END CLOSE curStockTransaction DEALLOCATE curStockTransaction END
Fetch data after and before '_' in SQL Server
I got the following entry in my database: I_ABC_2000.txt I want to trim the entry so I get: ABC So basically, I want everything after the first _ and before the 2nd _ . How can I do that?
There are possibly better ways to do this.. but one that I use is to use a scalar function . Create a scalar function and then call that function over your string CREATE FUNCTION [dbo].[fnParseString] ( #Section SMALLINT, #Delimiter CHAR, #Text varchar(1000) ) RETURNS VARCHAR(8000) AS BEGIN DECLARE #NextPos SMALLINT, #LastPos SMALLINT, #Found SMALLINT IF #Section > 0 SELECT #Text = REVERSE(#Text) SELECT #NextPos = CHARINDEX(#Delimiter, #Text, 1), #LastPos = 0, #Found = 1 WHILE #NextPos > 0 AND ABS(#Section) <> #Found SELECT #LastPos = #NextPos, #NextPos = CHARINDEX(#Delimiter, #Text, #NextPos + 1), #Found = #Found + 1 RETURN CASE WHEN #Found <> ABS(#Section) OR #Section = 0 THEN NULL WHEN #Section > 0 THEN REVERSE(SUBSTRING(#Text, #LastPos + 1, CASE WHEN #NextPos = 0 THEN DATALENGTH(#Text) - #LastPos ELSE #NextPos - #LastPos - 1 END)) ELSE SUBSTRING(#Text, #LastPos + 1, CASE WHEN #NextPos = 0 THEN DATALENGTH(#Text) - #LastPos ELSE #NextPos - #LastPos - 1 END) END END Then you can call the function over your text (the first argument is the position of the text you want, the second is the delimiter of your text and the thirst is the actual text) select dbo.[fnParseString] (1,'_','abra_ka_dabra') would return dabra select dbo.[fnParseString] (2,'_','abra_ka_dabra') would return ka etc.
Splitting a dynamic string
I need help parsing a dynamic string(see below). This string can change to only have one set of values to two, to three(like the one below). Raw String: valueA=valueB=valueC=valueD==valueE&valueA=valueB=valueC=valueD==valueE&valueA=valueB=valueC=valueD==valueE End Result: VelueB, ValueB, ValueB I have been able to extract valueA using the STUFF and CHARINDEX function(see below) but I'm having difficulty just getting valueB. I have also tried doing it in ssrs using the split function but getting nowhere. STUFF(( SELECT ',' + ' ' + SUBSTRING(param, 1, CHARINDEX('=', param) - 1) FROM dbo.Fn_mvparam(column_a, '&') AS fm FOR XML PATH('') ), 1, 1, ' ')
This should do the trick for you. Hope its useful to you CREATE FUNCTION uft_DoubleSplitter ( -- Add the parameters for the function here #String VARCHAR(4000), #Splitter1 CHAR, #Splitter2 CHAR ) RETURNS #Result TABLE (Id INT,MId INT,SValue VARCHAR(4000)) AS BEGIN DECLARE #FResult TABLE(Id INT IDENTITY(1, 1), SValue VARCHAR(4000)) DECLARE #SResult TABLE(Id INT IDENTITY(1, 1), MId INT, SValue VARCHAR(4000)) SET #String = #String+#Splitter1 WHILE CHARINDEX(#Splitter1, #String) > 0 BEGIN DECLARE #WorkingString VARCHAR(4000) = NULL SET #WorkingString = SUBSTRING(#String, 1, CHARINDEX(#Splitter1, #String) - 1) --Print #workingString INSERT INTO #FResult SELECT CASE WHEN #WorkingString = '' THEN NULL ELSE #WorkingString END SET #String = SUBSTRING(#String, LEN(#WorkingString) + 2, LEN(#String)) END IF ISNULL(#Splitter2, '') != '' BEGIN DECLARE #OStartLoop INT DECLARE #OEndLoop INT SELECT #OStartLoop = MIN(Id), #OEndLoop = MAX(Id) FROM #FResult WHILE #OStartLoop <= #OEndLoop BEGIN DECLARE #iString VARCHAR(4000) DECLARE #iMId INT SELECT #iString = SValue+#Splitter2, #iMId = Id FROM #FResult WHERE Id = #OStartLoop WHILE CHARINDEX(#Splitter2, #iString) > 0 BEGIN DECLARE #iWorkingString VARCHAR(4000) = NULL SET #IWorkingString = SUBSTRING(#iString, 1, CHARINDEX(#Splitter2, #iString) - 1) INSERT INTO #SResult SELECT #iMId, CASE WHEN #iWorkingString = '' THEN NULL ELSE #iWorkingString END SET #iString = SUBSTRING(#iString, LEN(#iWorkingString) + 2, LEN(#iString)) END SET #OStartLoop = #OStartLoop + 1 END INSERT INTO #Result SELECT MId AS PrimarySplitID, ROW_NUMBER() OVER (PARTITION BY MId ORDER BY Mid, Id) AS SecondarySplitID , SValue FROM #SResult END ELSE BEGIN INSERT INTO #Result SELECT Id AS PrimarySplitID, NULL AS SecondarySplitID, SValue FROM #FResult END RETURN Usage: --FirstSplit SELECT * FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===','&',NULL) --Second Split SELECT * FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===','&','=') Scenario Answer: SELECT fn.SValue FROM uft_DoubleSplitter('ValueA=ValueB=ValueC=ValueD==ValueE&ValueA=ValueB=ValueC===ValueE&ValueA=ValueB==ValueD===', '&', '=')AS fn WHERE fn.mid = 2
This should do it: REPLACE(#Param, "=", ", ")
Split and Replace the string in SqlServer 2008?
I want to split string 'GPIN-KH2-COH-24042014-02' by '-' in sqlserver 2008 and want to save in separate variables. How can I achieve this? Please help me in this regard. Now I am using below function and pass it ('GPIN-KH2-COH-24042014-02', '-') Create FUNCTION [dbo].[fnSplit] ( #strInputList NVARCHAR (MAX), -- List of Delimited Items #strDelimiter NVARCHAR (11) = ',' -- Delimiter that Separates Items ) RETURNS #tblList TABLE (strItem NVARCHAR(250)) BEGIN DECLARE #strItem NVARCHAR(MAX) WHILE CHARINDEX(#strDelimiter,#strInputList,0) <> 0 BEGIN SELECT #strItem = RTRIM(LTRIM( (SUBSTRING (#strInputList, 1, CHARINDEX (#strDelimiter, #strInputList, 0) -1)))), #strInputList = RTRIM(LTRIM( (SUBSTRING (#strInputList, CHARINDEX (#strDelimiter, #strInputList, 0) + LEN (#strDelimiter), LEN (#strInputList))))) IF LEN(#strItem) > 0 INSERT INTO #tblList SELECT #strItem END IF LEN(#strInputList) > 0 INSERT INTO #tblList SELECT #strInputList RETURN END Result: strItem GPIN KH2 COH 24042014 02 When I was delimeter and string it return result in that table format as shown above. But I want to get last two rows. How can I get this?
CRETAE function and pass your string and Delimiter as parameter FUNCTION: CREATE FUNCTION [dbo].[Split](#String varchar(8000), #Delimiter char(1)) returns #temptable TABLE (items varchar(8000)) as begin declare #idx int declare #slice varchar(8000) select #idx = 1 if len(#String)<1 or #String is null return while #idx!= 0 begin set #idx = charindex(#Delimiter,#String) if #idx!=0 set #slice = left(#String,#idx - 1) else set #slice = #String if(len(#slice)>0) insert into #temptable(Items) values(#slice) set #String = right(#String,len(#String) - #idx) if len(#String) = 0 break end return end And then call the function and use the values as you want DECLARE #A VARCHAR (100)= 'GPIN-KH2-COH-24042014-02' SELECT items INTO #STRINGS FROM dbo.split(#A,'-') select * from #STRINGS
Use this function, download from here usage SELECT DBO.fnString_DelimeterIndex(N'GPIN-KH2-COH-24042014-02','-',1) SELECT DBO.fnString_DelimeterIndex(N'GPIN-KH2-COH-24042014-02','-',2) SELECT DBO.fnString_DelimeterIndex(N'GPIN-KH2-COH-24042014-02','-',3) function ALTER FUNCTION [dbo].[fnString_DelimeterIndex] ( #Text NVARCHAR(4000), #Delimiter CHAR, #Section SMALLINT ) RETURNS NVARCHAR(4000) AS BEGIN DECLARE #NextPos SMALLINT, #LastPos SMALLINT, #Found SMALLINT, #REVERSE BIT IF #Section < 0 SELECT #Text = REVERSE(#Text)--, #Section=1,#REVERSE=1 SELECT #NextPos = CHARINDEX(#Delimiter, #Text, 1), #LastPos = 0, #Found = 1 WHILE #NextPos > 0 AND ABS(#Section) <> #Found SELECT #LastPos = #NextPos, #NextPos = CHARINDEX(#Delimiter, #Text, #NextPos + 1), #Found = #Found + 1 RETURN CASE WHEN #Found <> ABS(#Section) OR #Section = 0 THEN NULL --WHEN #REVERSE =1 THEN WHEN #Section > 0 THEN SUBSTRING(#Text, #LastPos + 1, CASE WHEN #NextPos = 0 THEN DATALENGTH(#Text) - #LastPos ELSE #NextPos - #LastPos - 1 END) ELSE REVERSE(SUBSTRING(#Text, #LastPos + 1, CASE WHEN #NextPos = 0 THEN DATALENGTH(#Text) - #LastPos ELSE #NextPos - #LastPos - 1 END)) END END
Here is a fancy way of solving it: You need a function to split it first: create function [dbo].[f_specialsplit] ( #param nvarchar(max), #delimiter char(1) ) returns #t table (val nvarchar(max), rn varchar(9)) as begin set #param += #delimiter ;with a as ( select cast(1 as bigint) f, charindex(#delimiter, #param) t where #param is not null union all select t + 1, charindex(#delimiter, #param, t + 1) from a where charindex(#delimiter, #param, t + 1) > 0 ) insert #t select substring(#param, f, t - f), row_number() over (order by (select 1)) from a option (maxrecursion 0) return end Trick is now to pivot the data into the variables: DECLARE #str varchar(100) = 'GPIN-KH2-COH-24042014-02' DECLARE #s1 varchar(100),#s2 varchar(100),#s3 varchar(100),#s4 varchar(100),#s5 varchar(100) SELECT #s1=[1],#s2=[2],#s3=[3],#s4=[4],#s5=[5] FROM f_specialsplit(#str,'-') PIVOT (min([val]) FOR rn in([1],[2],[3],[4],[5]) )AS p SELECT #s1,#s2,#s3,#s4,#s5 Result: GPIN KH2 COH 24042014 02