March 18, 2013 at 4:28 am
HI,
This is the table structure and script below:
CREATE TABLE [dbo].[GV_Booklet](
[BookletId] [int] IDENTITY(1,1) NOT NULL,
[LeafCount] [nchar](10) NULL,
[Denomination] [int] NULL,
[VoucherTypeId] [int] NOT NULL,
[VoucherNo] [varchar](20) NOT NULL,
[Quantity] [int] NULL,
[CreateDate] [datetime] NULL,
[ModifyDate] [datetime] NULL,
[ExpiryDate] [datetime] NULL,
[UserId] [int] NULL,
[VoucherStatusId] [int] NOT NULL,
[TransactionID] [varchar](20) NOT NULL,
CONSTRAINT [PK_GV_Booklet] PRIMARY KEY CLUSTERED
(
[BookletId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Script:
Declare @vouchertype varchar(20) = 'Percentage Discount',
@denomination int,
@userid int,
@voucherstatus int,
@transactionID varchar(20),
@quantity int = 2,
@count int =1,
@innercount int =1,
@leaf int =10,
@max-2 int
WHILE @count <= @quantity
BEGIN
WHILE @innercount < @leaf
BEGIN
SET @max-2 = (select vouchervaluebased from gv_maxvouchervalue)
SET @transactionID = (select vouchertransactionID from gv_maxvouchervalue)
INSERT INTO GV_Booklet
VALUES
(
@leaf,
100,
1,
'VB' + Replace( Str( @max-2+1, 7), ' ', '0') ,
@quantity,
GETDATE(),
GETDATE(),
DATEADD(MM,6,GETDATE()),
1,
1,
'TRN' + Replace( Str( @transactionID + 1, 7), ' ', '0')
)
SET @innercount = @innercount + 1
UPDATE gv_maxvouchervalue
SET vouchervaluebased = @max-2 + 1
END
SET @innercount = 1
SET @count = @count + 1
END
UPDATE gv_maxvouchervalue
SET vouchertransactionID = @transactionID + 1
select * from GV_Booklet
Now let me explain you guys the scenario-- This query is for a voucher booklet. If the quantity is 2 and leaf ( describing pages in a booklet) is 10 then 20 unique vouchersno should get generated with 2 unique Transactionno as quantity of booklet is 2. How to achieve this?
plz help
_______________________________________________________________
To get quick answer follow this link:
http://www.sqlservercentral.com/articles/Best+Practices/61537/
March 18, 2013 at 4:57 am
This should get you started:
-- Inline tally from Jeff Moden et al.
DECLARE
@LastBookNo INT = 23,
@LastPageNo INT = 80,
@BooksToInsert INT = 2,
@PagesPerBook INT = 10
;WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
Booklets AS (SELECT TOP (@BooksToInsert) BookNo = @LastBookNo + ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM E4),
Pages AS (SELECT TOP (@PagesPerBook) N FROM E4)
SELECT
BookNo,
PageNo = @LastPageNo + ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
FROM Booklets b
CROSS JOIN Pages p
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
March 19, 2013 at 1:52 am
kapil_kk (3/18/2013)
...How to achieve this?plz help
Do you need help with the stub code I posted?
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
March 19, 2013 at 2:21 am
ChrisM@Work (3/19/2013)
kapil_kk (3/18/2013)
...How to achieve this?plz help
Do you need help with the stub code I posted?
Thanks Chris, I have implemented that thing....
But I am not clear why you posted that code
_______________________________________________________________
To get quick answer follow this link:
http://www.sqlservercentral.com/articles/Best+Practices/61537/
March 19, 2013 at 6:34 am
kapil_kk (3/19/2013)
ChrisM@Work (3/19/2013)
kapil_kk (3/18/2013)
...How to achieve this?plz help
Do you need help with the stub code I posted?
Thanks Chris, I have implemented that thing....
But I am not clear why you posted that code
It's a set-based replacement for this crazy nested loop structure:
WHILE @count <= @quantity
BEGIN
WHILE @innercount < @leaf
BEGIN
SET @max-2 = (select vouchervaluebased from gv_maxvouchervalue)
SET @transactionID = (select vouchertransactionID from gv_maxvouchervalue)
INSERT INTO GV_Booklet
VALUES
(
@leaf,
100,
1,
'VB' + Replace( Str( @max-2+1, 7), ' ', '0') ,
@quantity,
GETDATE(),
GETDATE(),
DATEADD(MM,6,GETDATE()),
1,
1,
'TRN' + Replace( Str( @transactionID + 1, 7), ' ', '0')
)
SET @innercount = @innercount + 1
UPDATE gv_maxvouchervalue
SET vouchervaluebased = @max-2 + 1
END
SET @innercount = 1
SET @count = @count + 1
END
The set-based version would be much faster and, in my opinion, considerably easier to maintain.
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
March 19, 2013 at 6:58 am
ChrisM@Work (3/19/2013)
kapil_kk (3/19/2013)
ChrisM@Work (3/19/2013)
kapil_kk (3/18/2013)
...How to achieve this?plz help
Do you need help with the stub code I posted?
Thanks Chris, I have implemented that thing....
But I am not clear why you posted that code
It's a set-based replacement for this crazy nested loop structure:
WHILE @count <= @quantity
BEGIN
WHILE @innercount < @leaf
BEGIN
SET @max-2 = (select vouchervaluebased from gv_maxvouchervalue)
SET @transactionID = (select vouchertransactionID from gv_maxvouchervalue)
INSERT INTO GV_Booklet
VALUES
(
@leaf,
100,
1,
'VB' + Replace( Str( @max-2+1, 7), ' ', '0') ,
@quantity,
GETDATE(),
GETDATE(),
DATEADD(MM,6,GETDATE()),
1,
1,
'TRN' + Replace( Str( @transactionID + 1, 7), ' ', '0')
)
SET @innercount = @innercount + 1
UPDATE gv_maxvouchervalue
SET vouchervaluebased = @max-2 + 1
END
SET @innercount = 1
SET @count = @count + 1
END
The set-based version would be much faster and, in my opinion, considerably easier to maintain.
Ok, thanks Chris....
can you plz tell me how to convert mine loop based script into a set based approach... It will be very helpful for me in the future
_______________________________________________________________
To get quick answer follow this link:
http://www.sqlservercentral.com/articles/Best+Practices/61537/
March 19, 2013 at 7:19 am
Have a play with this;
DECLARE
@LastBookNo INT = 23,
@LastPageNo INT = 80,
@BooksToInsert INT = 2,
@PagesPerBook INT = 10
;WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
Booklets AS (SELECT TOP (@BooksToInsert) BookNo = @LastBookNo + ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM E4),
Pages AS (SELECT TOP (@PagesPerBook) N FROM E4)
SELECT
@PagesPerBook ,
100,
1,
'VB' + CAST(@LastPageNo + ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS VARCHAR(6)),
@BooksToInsert,
GETDATE(),
GETDATE(),
DATEADD(MM,6,GETDATE()),
1,
1,
'TRN' + CAST(b.BookNo AS VARCHAR(6))
FROM Booklets b
CROSS JOIN Pages p
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
March 19, 2013 at 7:57 pm
Chris, although your code is better, I can understand why it's confusing to newer SQL coders. I think it's less intuitive, and not everyone is familiar with some of the newer options in SQL. It doesn't have a simple flow from top to bottom that some are used to.
Perhaps you could add some comments or narrative to explain how it is the equivalent to the OP loop code ?
March 20, 2013 at 7:56 am
homebrew01 (3/19/2013)
Chris, although your code is better, I can understand why it's confusing to newer SQL coders. I think it's less intuitive, and not everyone is familiar with some of the newer options in SQL. It doesn't have a simple flow from top to bottom that some are used to.Perhaps you could add some comments or narrative to explain how it is the equivalent to the OP loop code ?
Sure! Thank you for the suggestion. Let's start with this and see if any questions pop up;
DECLARE
@LastBookNo INT = 23,
@LastPageNo INT = 80,
@BooksToInsert INT = 2,
@PagesPerBook INT = 10
;WITH
-- Make an inline tally table (CTE)
E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
-- Use the tally CTE to construct a booklets CTE
-- containing one row for each booklet required, in this case, 2 booklets.
-- Adding the row number to the last book number (obtained elsewhere) yields
-- the new book numbers
Booklets AS (SELECT TOP (@BooksToInsert) BookNo = @LastBookNo + ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM E4),
-- use the tally CTE to construct a Pages CTE containing one row per page required
-- in this case, 10 pages per book
Pages AS (SELECT TOP (@PagesPerBook) N FROM E4)
-- cross join the Booklets CTE (2 rows) and the Pages CTE (10 rows) to generate 20 rows.
-- We've already calculated the two new BookNo values in the Booklets CTE
-- In this query we perform the same type of operation with the page number
-- ROW_NUMBER() numbers the rows 1 to 20, added to @LastPageNo gives the new page number
SELECT
@PagesPerBook ,
100,
1,
'VB' + CAST(@LastPageNo + ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS VARCHAR(6)),
@BooksToInsert,
GETDATE(),
GETDATE(),
DATEADD(MM,6,GETDATE()),
1,
1,
'TRN' + CAST(b.BookNo AS VARCHAR(6))
FROM Booklets b
CROSS JOIN Pages p
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
May 8, 2013 at 8:16 am
oopes I am getting error:
Cannot insert duplicate key row in object 'dbo.GV_Booklet' with unique index 'UN_GVBooklet_VoucherNo'. The duplicate key value is (BVD0002789).
ALTER procedure [dbo].[BS_Voucher_CreateBooklet]
@vouchertypeID int =2,
@denomination int = 555,
@quantity int = 3,
@amountvalue int =0,
@leaf int =2,
@userid varchar(50) =1,
@ValidateDays int =30
AS
BEGIN
SET NOCOUNT ON;
DECLARE
--@vouchertype varchar(20),
@transactionID varchar(20),
--@count int =1,
--@innercount int =1,
@VoucherNumber int,
--@max int,
@vouchertypenew varchar(20),
@retval varchar(20),
@BookletID int = 0,
@VoucherStatus int
-- table variables receive OUTPUT
DECLARE @VoucherNumberTable TABLE (vouchervalue INT);
DECLARE @transactionIDTable TABLE (transactionID INT);
DECLARE @BookletIDTable TABLE (BookletID int);
SELECT
@vouchertypenew = SUBSTRING(TrimmedVoucherType,1+CHARINDEX(' ',TrimmedVoucherType,1),20),
@retval = LEFT(TrimmedVoucherType,1)
+ ISNULL(SUBSTRING(TrimmedVoucherType,1+NULLIF(CHARINDEX(' ',TrimmedVoucherType,1),0),1),'')
FROM GV_VoucherType v
CROSS APPLY (SELECT TrimmedVoucherType = LTRIM(RTRIM(v.vouchertype))) x
WHERE v.VoucherTypeID = @vouchertypeID;
--If @vouchertypenew IS NULL
--Return -1
SELECT @voucherstatus = VoucherStatusId FROM GV_VoucherStatus WHERE VoucherStatus = 'New';
------------------------------------------------------------------------------
--Read Existing Booklet ID and set next @quantity
------------------------------------------------------------------------------
--SET @BookletID = (SELECT ISNULL(MAX(RIGHT(BookletID,5)),0) FROM GV_Booklet)
Update Gv_VoucherValue
SET VoucherValue = ISNULL(VoucherValue,0)+ @quantity
OUTPUT deleted.VoucherValue INTO @BookletIDTable
WHERE VoucherAbbreviation = 'BOKID'
SELECT @BookletID = ISNULL(BookletID,0) FROM @BookletIDTable
--------------------------------------------------------------------------------------
-- Read existing @VoucherNumber, set next @VoucherNumber
--------------------------------------------------------------------------------------
-- save off the current value to @VoucherNumber
-- and update to the next available value
UPDATE gv_vouchervalue
SET vouchervalue = ISNULL(vouchervalue,0) + @leaf
OUTPUT deleted.vouchervalue INTO @VoucherNumberTable
WHERE voucherabbreviation = 'B' + @retval;
SELECT @VoucherNumber = ISNULL(vouchervalue,0) FROM @VoucherNumberTable;
--------------------------------------------------------------------------------------
-- Read existing @transactionID, set next @transactionID
--------------------------------------------------------------------------------------
-- save off the current value to @transactionID
-- and update to the next available value
UPDATE gv_vouchervalue
SET VoucherValue = VoucherValue + 1
OUTPUT deleted.vouchervalue INTO @transactionIDTable
WHERE VoucherAbbreviation = 'TRNID'
SELECT @transactionID = ISNULL(transactionID,0) FROM @transactionIDTable;
--------------------------------------------------------------------------------------
-- Insert required number of rows into GV_Voucher
--------------------------------------------------------------------------------------
-- Inline tally table generates (@quantity) rows
BEGIN Tran
;WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1),
E2(N) AS (SELECT 1 FROM E1 a, E1 b),
E3(N) AS (SELECT 1 FROM E2 a , E2 b, E2 c),
--iTally(N) AS (SELECT n = ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) FROM E2 a, E2 b, E2 c),
Booklets as (SELECT TOP(@quantity) Bookno = @BookletID + ROW_NUMBER() OVER (ORDER BY(SELECT NULL))FROM E2),
Pages AS (SELECT TOP(@leaf) N FROM E3)
--select N from E3
INSERT INTO GV_Booklet
SELECT
'B'+ REPLACE(STR(CONVERT(varchar,BookNo),5),' ','0') ,
@leaf,
@denomination,
@vouchertypeID,
'B' + @retval + REPLACE(STR( CAST(@VoucherNumber + ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS VARCHAR(10)),7),' ','0'),
--'B' + @retval + CAST(@VoucherNumber + ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS VARCHAR(10)) ,
@quantity,
GETDATE(),
GETDATE(),
DATEADD(MM,6,GETDATE()),
@VoucherStatus,
'TRN' + Replace( Str( @transactionID + 1, 7), ' ', '0'),
@amountvalue,
0,
@ValidateDays
FROM Booklets b
CROSS JOIN Pages p
COMMIT TRAN
--select * from GV_Booklet
END
--truncate table GV_Booklet
_______________________________________________________________
To get quick answer follow this link:
http://www.sqlservercentral.com/articles/Best+Practices/61537/
May 8, 2013 at 8:38 am
I think the prob is this part:
INSERT INTO GV_Booklet
SELECT
'B'+ REPLACE(STR(CONVERT(varchar,BookNo),5),' ','0') ,
@leaf,
@denomination,
@vouchertypeID,
'B' + @retval + REPLACE(STR(@VoucherNumber + p.N ,7),' ','0'),
--'B' + @retval + CAST(@VoucherNumber + ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS VARCHAR(10)) ,
@quantity,
GETDATE(),
GETDATE(),
DATEADD(MM,6,GETDATE()),
@VoucherStatus,
'TRN' + Replace( Str( @transactionID + 1, 7), ' ', '0'),
@amountvalue,
0,
@ValidateDays
FROM Booklets b
CROSS JOIN Pages p
_______________________________________________________________
To get quick answer follow this link:
http://www.sqlservercentral.com/articles/Best+Practices/61537/
May 8, 2013 at 8:54 am
It's going to take far less time and will be far less painful (for me) if I have tables and data to test against. Please can you read the link in my signature block, "please read this". It will show you how to write table creation scripts - which I think you already know - and also how to write scripts to populate those tables with data. The end result should be a statement batch that folks can copy and paste into SSMS and run without errors using the same SQL Server version as you are using.
It might take you a couple of hours but it will be well worth your time - and mine 😀
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
May 8, 2013 at 9:20 am
And don't forget to post the expected results based on the sample data you provide. That will help with testing.
May 8, 2013 at 11:20 pm
Hi Chris. I trie to play with tally script ans found that bouvherno are not generating new everytime when we run it.. it is returning same values due to that Unique constraint does not allow duplicate values error is coming..
SELECT
'B'+ REPLACE(STR(CONVERT(varchar,BookNo),5),' ','0') ,
@leaf,
@denomination,
@vouchertypeID,
'B' + @retval + REPLACE(STR(@VoucherNumber + ROW_NUMBER() OVER (ORDER BY p.n) ,7),' ','0') VoucherNo,
--'B' + @retval + CAST(@VoucherNumber + ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS VARCHAR(10)) ,
@quantity,
GETDATE(),
GETDATE(),
DATEADD(MM,6,GETDATE()),
@VoucherStatus,
'TRN' + Replace( Str( @transactionID + 1, 7), ' ', '0'),
@amountvalue,
0,
@ValidateDays
FROM Booklets b
CROSS JOIN Pages p
When i ran the script for the first time it give me data like this:
(No column name) (No column name) (No column name) (No column name) VoucherNo (No column name) (No column name) (No column name) (No column name) (No column name) (No column name) (No column name) (No column name) (No column name) (No column name) (No column name)
B00037 2 555 2 BVD0000025 3 2013-05-09 10:50:30.153 2013-05-09 10:50:30.153 2013-11-09 10:50:30.153 1 TRN0000013 0 1 1 0 30
B00037 2 555 2 BVD0000026 3 2013-05-09 10:50:30.153 2013-05-09 10:50:30.153 2013-11-09 10:50:30.153 1 TRN0000013 0 1 1 0 30
B00038 2 555 2 BVD0000027 3 2013-05-09 10:50:30.153 2013-05-09 10:50:30.153 2013-11-09 10:50:30.153 1 TRN0000013 0 1 1 0 30
B00038 2 555 2 BVD0000028 3 2013-05-09 10:50:30.153 2013-05-09 10:50:30.153 2013-11-09 10:50:30.153 1 TRN0000013 0 1 1 0 30
B00039 2 555 2 BVD0000029 3 2013-05-09 10:50:30.153 2013-05-09 10:50:30.153 2013-11-09 10:50:30.153 1 TRN0000013 0 1 1 0 30
B00039 2 555 2 BVD0000030 3 2013-05-09 10:50:30.153 2013-05-09 10:50:30.153 2013-11-09 10:50:30.153 1 TRN0000013 0 1 1 0 30
Next time when i ran it again it gives data like :
(No column name) (No column name) (No column name) (No column name) VoucherNo (No column name) (No column name) (No column name) (No column name) (No column name) (No column name) (No column name) (No column name) (No column name) (No column name) (No column name)
B00040 2 555 2 BVD0000027 3 2013-05-09 10:51:39.317 2013-05-09 10:51:39.317 2013-11-09 10:51:39.317 1 TRN0000014 0 1 1 0 30
B00040 2 555 2 BVD0000028 3 2013-05-09 10:51:39.317 2013-05-09 10:51:39.317 2013-11-09 10:51:39.317 1 TRN0000014 0 1 1 0 30
B00041 2 555 2 BVD0000029 3 2013-05-09 10:51:39.317 2013-05-09 10:51:39.317 2013-11-09 10:51:39.317 1 TRN0000014 0 1 1 0 30
B00041 2 555 2 BVD0000030 3 2013-05-09 10:51:39.317 2013-05-09 10:51:39.317 2013-11-09 10:51:39.317 1 TRN0000014 0 1 1 0 30
B00042 2 555 2 BVD0000031 3 2013-05-09 10:51:39.317 2013-05-09 10:51:39.317 2013-11-09 10:51:39.317 1 TRN0000014 0 1 1 0 30
B00042 2 555 2 BVD0000032 3 2013-05-09 10:51:39.317 2013-05-09 10:51:39.317 2013-11-09 10:51:39.317 1 TRN0000014 0 1 1 0 30
_______________________________________________________________
To get quick answer follow this link:
http://www.sqlservercentral.com/articles/Best+Practices/61537/
May 8, 2013 at 11:42 pm
oopes there was problem in this
UPDATE gv_vouchervalue
SET vouchervalue = ISNULL(vouchervalue,0) + (@leaf * @quantity)
OUTPUT deleted.vouchervalue INTO @VoucherNumberTable
WHERE voucherabbreviation = 'B' + @retval;
SELECT @VoucherNumber = ISNULL(vouchervalue,0) FROM @VoucherNumberTable;
in Gv_vouchervalue it was updating value on basis of leaf only due to that duplicate value were inserting....
its done now :-):-D
_______________________________________________________________
To get quick answer follow this link:
http://www.sqlservercentral.com/articles/Best+Practices/61537/
Viewing 15 posts - 1 through 14 (of 14 total)
You must be logged in to reply to this topic. Login to reply