-1

I create a procedure to consolidate all info calculated per each X & Y value combinations. I use a simple indexing to fetch the values of X & Y by using 2-step WHILE loops.

Here are the X & Y support tables:

X & Y

However, the result is below as [MAIN_TABLE]. However, I expect it to be the all combinations of X & Y.

Result

Here is my code:

ALTER PROCEDURE [dbo].[CONSOLIDATION_Procedure]     
AS
BEGIN
    
    IF OBJECT_ID('dbo.[MAIN_TABLE]', 'U') IS NOT NULL
         DELETE FROM [MAIN_TABLE]
    
    DECLARE @IndexX INT SET @IndexX=1
    DECLARE @IndexY INT SET @IndexY=1
    DECLARE @IndexX_Max INT SET @IndexX_Max = (SELECT MAX([Index]) FROM [temp_X_Index])
    DECLARE @IndexY_Max INT SET @IndexY_Max = (SELECT MAX([Index]) FROM [temp_Y_Index])
    
    WHILE @IndexX <= @IndexX_Max 
    BEGIN         
        DECLARE @XVal VARCHAR(20) SET @XVal = (SELECT [X_VAL] FROM [temp_X_Index] WHERE [INDEX]=@IndexX)
    
        WHILE @IndexY <= @IndexY_Max 
        BEGIN         
            DECLARE @YVAL VARCHAR(20) SET @YVAL = (SELECT [Y_VAL] FROM [temp_Y_Index] WHERE [INDEX]=@IndexY)            
            INSERT INTO [MAIN_TABLE]        
                SELECT * FROM [dbo].[SUPPORT_TABLE] WHERE [X] = @XVal AND [Y]= @YVAL
        
        SET @IndexY = @IndexY+1
        END
    
    SET @IndexX = @IndexX+1
    END
    
  END
0

1 Answer 1

4

You can use a Cartesian product(cross join) instead of this block code to generate it.

SELECT x.[index] x_index, y.[index] as y_index, x_val, y_val
  FROM [temp_X_Index] x
 CROSS JOIN [temp_Y_Index] y
Sign up to request clarification or add additional context in comments.

7 Comments

Can also use cross join to mean the same thing (bit more explicit)
Specifically I think @tinazmu means use this syntax FROM X CROSS JOIN Y it makes the meaning a little more obvious
@Nick.McDermaid and tinazmu I update to with that keyword
@BTurkeli I mean this code will do all you need to do.
@BTurkeli it is very rare you ever need a WHILE loop in SQL. SQL is a set-based language, and so it excels at set-based operations; a WHILE is the opposite to that methodology. If you are considering using a WHILE when writing SQL, you are very likely making the wrong decisions.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.