我想从 SQL Server 进行特殊查询。它来自2张桌子:
- 有列的猫表
catParentId
- 与
catId
列相关的消息表
我想通过 catId 获取与该类别相关的最后一条消息详细信息的猫。换句话说,我想获得父猫下每只猫的最后一条消息。
我创建了表变量并将值插入其中。这是最好的表现方式吗?
SP代码:
USE [Lovely_umbraco_cms]
GO
/****** Object: StoredProcedure [dbo].[SP_Categories_GetCatsMsgs] Script Date: 12/30/2012 01:21:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_Categories_GetCatsMsgs]
@CatId int
AS
set @catId =1;
declare @CatMessages Table(
RowID INT IDENTITY ( 1 , 1 ),
CatName Nvarchar(50),
MessageCount int,
LastMessageName nvarchar(50),
OwnerID uniqueidentifier,
CreatedDate date,
Watched int,
commentCount int
)
--------------- @CatTable --------
declare @RowsCount int;
Set @rowscount =1;
declare @CatTable table(
id int identity(1,1),
catId int,
CatName nvarchar(50),
CatParentId int
);
--- Insert into @CatTable
insert into @CatTable(catId,catName,CatParentId )
select catId, CatName ,CatParentId from LS_Categories WHERE(CatParentId = @CatId);
-----------------------------------
declare @CatTableID int;
declare @CatName nvarchar(50);
-------Temp Message Table --------
declare @Temp_MessagesTable table(
[Subject] nvarchar(255),
[Date] [nvarchar](15) NULL,
[OwnerId] [uniqueidentifier] NULL,
[WatchCount] [bigint] NULL
);
--------------- @CatMessages Varibles-----
declare @MessageCount int;
declare @LastMessageName nvarchar(50);
declare @OwnerID uniqueidentifier;
declare @CreatedDate date;
declare @Watched int;
declare @commentCount int;
-------
while @rowsCount <=(SELECT count(Catid) FROM @CatTable)
begin
select @CatTableID = CatId, @CatName = CatName from @CatTable where id= @rowsCount;
delete from @Temp_MessagesTable;
insert into @Temp_MessagesTable ([Subject],[Date],[OwnerId],[WatchCount])(
SELECT Subject, Date, OwnerId, WatchCount
FROM (SELECT TOP (1) Subject, Date, OwnerId, WatchCount
FROM LS_Mssages
WHERE (CatId = @CatTableID) ORDER BY MsgId DESC
) as s
);
select @LastMessageName=[Subject],@CreatedDate=[Date],
@OwnerID=[OwnerId],@Watched= [WatchCount] from @Temp_MessagesTable
-- insert into CatMessages Table
insert into @CatMessages(CatName,MessageCount,LastMessageName,OwnerID,CreatedDate,Watched,commentCount)
(select @CatName,@MessageCount,@LastMessageName,@OwnerID,@CreatedDate,@Watched,@commentCount);
set @rowsCount = @rowsCount+1
End
select * from @CatMessages;
我的表:http ://ss-projects.com/t1.jpg