Click here to Skip to main content
15,887,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
lets say N=2

expected output
1  2  
2  4
3  6
4  8
5  10
6  12
7  14
8  16
9  18
10  20

and then in next column i want sum of both columns or n number of columns.

What I have tried:

SQL
ALTER procedure [dbo].[project]

	@N int

AS

BEGIN
	declare @tbl1 table(ID int identity(1,1), MT int )
	declare @tbl2 table(ID int identity(1,1), MT int)
	declare @T int
	declare @i int, @j int
	set @i=1
	while @i<=@N
	begin			
		set @j=1
			while @j<=10
			begin
				set @T=@i*@j
				insert into @tbl1 values(@T)
				set @j=@j+1
			end
		select *from @tbl1
		set @i=@i+1
	end	
END 


above code creates multiplication output but in different tables, please suggest a solution with query.
Posted
Updated 17-Mar-18 2:56am
v2
Comments
Siddharth_Gupta 17-Mar-18 5:44am    
I guess I figured a way around the problem, below is the code I used:
ALTER procedure [dbo].[project]

@N int

AS

BEGIN
declare @tbl table (ID int identity(1,1),x1 int, x2 int, x3 int, x4 int, x5 int, x6 int, x7 int, x8 int, x9 int, x10 int,sumall int)
declare @tbl1 table (ID int identity(1,1),ttl int)
declare @amount int
declare @T int
declare @x int, @y int
set @x=1
set @y=1
while @y<=@N
begin
set @T=@x*@y
insert into @tbl values(@T, @T*2, @T*3, @T*4, @T*5, @T*6, @T*7, @T*8, @T*9, @T*10,@T+ @T*2+ @T*3+ @T*4+ @T*5+ @T*6+ @T*7+ @T*8+ @T*9+ @T*10)
end
select *from @tbl
END


//If anyone has a better work around then please do share//
#realJSOP 17-Mar-18 11:54am    
Look at my solution.

1 solution

Try this:

SQL
DECLARE @n INT = 2;

;WITH cte AS
(
    -- create a common table expression with ten rows with the "Value" column 
    -- being set to the row number
    SELECT TOP(10) Value = ROW_NUMBER() 
    OVER (ORDER BY[object_id]) FROM SYS.ALL_OBJECTS
)
-- and then select the rows, identify the mulitplier (@n), and set the result
SELECT Value,
       @n AS Multiplier,
       Value * @n AS Result
FROM   cte;


You should end up with 10 rows that show the value (1-10), the multiplier (in this case, it's 2), and the result of multiplying the value by the multiplier.

If you want more than 10 rows, just change the TOP(10) clause to the reflect the desired value.
 
Share this answer
 
v4
Comments
Maciej Los 17-Mar-18 8:56am    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900