简体   繁体   中英

How to write a stored procedure

I'm trying to write a sp. My requirement is mentioned below:

TableA:

Id is Primary key.

+----+---------+
| Id |  Col1   |
+----+---------+
|  1 | Sample1 |
|  2 | Sample2 |
+----+---------+

TableB:

Id is Primary key. Col1_Id is foreign key of TableA

+----+---------+-------+
| Id | Col1_Id | Col2  |
+----+---------+-------+
|  1 |       1 | TestA |
|  2 |       1 | TestB |
|  3 |       2 | TestC |
+----+---------+-------+

TableC:

Id is Primary key.

+----+------------------------+
| Id |     QusetionText       |
+----+------------------------+
|  1 | Sample Question One?   |
|  2 | Sample Question Two?   |
|  3 | Sample Euestion Three? |
+----+------------------------+

My Output Should be; TableD:

Id is Primary key. Col1_Id is foreign key of TableA Col2_Id is foreign key of TableB

+----+------------+---------+---------+------------------------+
| Id | QuestionId | Col1_Id | Col2_Id |      QusetionText      |
+----+------------+---------+---------+------------------------+
|  1 | Q_2013     |       1 |       1 | Sample Question One?   |
|  2 | Q_2013     |       1 |       1 | Sample Question Two?   |
|  3 | Q_2013     |       1 |       1 | Sample Question Three? |
|  4 | Q_2013     |       1 |       2 | Sample Question One?   |
|  5 | Q_2013     |       1 |       2 | Sample Question Two?   |
|  6 | Q_2013     |       1 |       2 | Sample Question Three? |
|  7 | Q_2013     |       2 |       3 | Sample Question One?   |
|  8 | Q_2013     |       2 |       3 | Sample Question Two?   |
|  9 | Q_2013     |       2 |       3 | Sample Question Three? |
+----+------------+---------+---------+------------------------+

Please tell me how to write query to get TableD.

Thank you all in advance for your response.

Check This Out,

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Prathiba
-- Create date: 
-- Description: 
-- =============================================
 CREATE PROCEDURE SampleProc 

 AS
 BEGIN
SET NOCOUNT ON;
           SELECT dbo.TableA.Id, dbo.TableB.Col1_Id, dbo.TableC.Id AS Col2_Id, dbo.TableC.QuestionText
           FROM   dbo.TableA INNER JOIN
                  dbo.TableB ON dbo.TableA.Id = dbo.TableB.Col1_Id CROSS JOIN
                  dbo.TableC
 END
 GO

Please make sure that there is no relation with your TableC ie., why cross join is using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM