2
CREATE TABLE [dbo].[test](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[ctext] [varchar](12) NOT NULL,
 CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED 
(
[id] ASC
))

CREATE TABLE [dbo].[Comments](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[cComments] [varchar](250) NOT NULL,
[fk_test] [bigint] NOT NULL)
GO

ALTER TABLE [dbo].[Comments]  WITH CHECK ADD  CONSTRAINT [FK_Comments_test] FOREIGN KEY([fk_test])
REFERENCES [dbo].[test] ([id])
ON DELETE CASCADE

两个表以正常的一对多关系链接。

我想要一个返回列表列表的 Select:

-----------------------------------------------------
|test.id|test.cnumber|comments.id|comments.cComments|
|-------|------------|-----------|------------------|
| 1     | mytest1    |     1     |   comment1       |
|       |            |     2     |   comment2       |
|       |            |     3     |   comment3       |
|       |            |     4     |   comment4       |
|       |            |     5     |   comment5       |
|       |            |     6     |   comment6       |
| 2     | mytest2    |     7     |   comment7       |
|       |            |     8     |   comment8       |
| 3     | mytest3    |     7     |   comment9       |
-----------------------------------------------------

有什么办法吗?

我试图用 sql 存储过程替换 linq。

4

1 回答 1

2

试试这个解决方案 -

DECLARE @test TABLE 
(
  [id] [bigint] IDENTITY(1,1) NOT NULL
, [ctext] [varchar](12) NOT NULL
)

DECLARE @Comments TABLE
(
[id] [bigint] IDENTITY(1,1) NOT NULL,
[cComments] [varchar](250) NOT NULL,
[fk_test] [bigint] NOT NULL
)


INSERT INTO @test (ctext)
VALUES ('1'), ('2')

INSERT INTO @Comments (cComments, fk_test)
VALUES ('123', 1), ('123', 1), ('123', 2), ('123', 2)

SELECT  id = CASE WHEN d.rcount = 1 THEN d.id END
, cnumber = CASE WHEN d.rcount = 1 THEN d.cnumber  END
, d.commentid
, d.cComments
FROM (
SELECT 
   t.id
 , cnumber = t.ctext
 , commentid = c.id
 , c.cComments
 , rcount = ROW_NUMBER() OVER (PARTITION BY t.[id] ORDER BY t.[id] DESC)
FROM @test t
JOIN @Comments c ON t.id = c.fk_test
) d
于 2013-04-10T12:31:25.417 回答