Tuesday, July 31, 2018

Stored Procedure for iterating[For Each row] in temp table values in SQL



USE [DBName]
GO
/****** Object:  StoredProcedure [dbo].[GetselectedEcoNoFromkeywords]    Script Date: 07/31/2018 04:21:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GetselectedEcoNoFromkeywords]
@keywordsIds varchar(max)

as
Declare @Id varchar(100);
Declare @tempTb Table (id integer);

--Inserting ids values into temp table from dbo.BreakStringIntoTableRows(@val) function
-- this function (dbo.BreakStringIntoTableRows) is created for the splitting the ids values into table, which are comming as sp paramenter like '1023, 234,478'

Insert into @tempTb SELECT *  FROM  dbo.BreakStringIntoTableRows(@keywordsIds)
--select * from @tId

CREATE TABLE #ecoNo(
ECONo varchar(255),
Title varchar(max),
    ProjectId varchar(255),
   -- PROJECT_NO varchar(255),
   -- KEYWORDID varchar(255),
   -- cat_description varchar(255)
    );

While (Select Count(*) From @tempTb) >0
Begin
    Select @Id = Id From @tempTb

    -- Inserting and clubing values here in eco temp table
   
   
        INSERT INTO  #ecoNo SELECT
       
        CASE WHEN LEN(CONVERT(nvarchar(50), PROJECT_NO)) >=5 THEN
CASE WHEN LEN(CONVERT(nvarchar(50), INCREMENT_NO)) >=3 THEN
(CONVERT(nvarchar(50),PROJECT_NO) +'-' +CONVERT(nvarchar(50),INCREMENT_NO)+CONVERT(nvarchar(50),AMENDMENT_NO))
ELSE
(CONVERT(nvarchar(50),PROJECT_NO) +'-' +RIGHT('000' + CONVERT(nvarchar(50), INCREMENT_NO), 3)+CONVERT(nvarchar(50),AMENDMENT_NO))
END
        ELSE
CASE WHEN LEN(CONVERT(nvarchar(50), INCREMENT_NO)) >=3 THEN
(RIGHT('00000' + CONVERT(nvarchar(50), PROJECT_NO), 5) +'-' +CONVERT(nvarchar(50),INCREMENT_NO)+CONVERT(nvarchar(50),AMENDMENT_NO))
ELSE
(RIGHT('00000' + CONVERT(nvarchar(50), PROJECT_NO), 5) +'-' +RIGHT('000' + CONVERT(nvarchar(50), INCREMENT_NO), 3)+CONVERT(nvarchar(50),AMENDMENT_NO))
END
        END

        AS ECONo,PROJECT_NAME As Title, PROJECT.PROJECTID as ProjectId
FROM project, proj_keyword, cat_keyword
WHERE keywordid in(@id) and
PROJECT.PROJECTID = proj_keyword.projectid
AND proj_keyword.keywordid = cat_keyword.catid

    Delete @tempTb Where Id = @Id

End

select * from #ecoNo

-- exec[GetselectedEcoNoFromkeywords] '1025,1021'

No comments:

Post a Comment