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
データ サンプル: http://ss-projects.com/data.jpg