从db到sql变量中选择5条记录

时间:2013-10-03 19:28:07

标签: sql sql-server

我有一个sql脚本,它会从表中提取记录,我希望它从表中读取5条记录,其中Id = 4然后存储Id以便稍后在脚本中使用

DECLARE @ITEM1 INT
DECLARE @ITEM2 INT
DECLARE @ITEM3 INT
DECLARE @ITEM4 INT
DECLARE @ITEM5 INT

SET @ITEM1 = (SELECT Id FROM dbo.PageElement WHERE TypeId = 4)
SET @ITEM2 = (SELECT Id FROM dbo.PageElement WHERE TypeId = 4)
SET @ITEM3 = (SELECT Id FROM dbo.PageElement WHERE TypeId = 4)
SET @ITEM4 = (SELECT Id FROM dbo.PageElement WHERE TypeId = 4)
SET @ITEM5 = (SELECT Id FROM dbo.PageElement WHERE TypeId = 4)

我不确定读取我的5个变量中的Id值的最佳方法

3 个答案:

答案 0 :(得分:4)

为什么不使用表变量(或临时表)

declare @Temp_Items (ID int primary key, Num int identity(1, 1))

insert into @Temp_Items
select top 5 ID from dbo.PageElement where TypeId = 4

所以你将有5行由Num计算。顺便说一句,通常最好在查询中添加order by

现在,您可以像@Item<N>一样抓取select ID from @Temp_Items where Num = N

答案 1 :(得分:0)

Select Top 5 from dbo.PageElement WHERE TypeId = 4

这是最简单的方法

Select Top 5 Id from dbo.PageElement WHERE TypeId = 4


SET @ITEM1 = (SELECT Top 1 Id FROM dbo.PageElement WHERE TypeId = 4)
SET @ITEM2 = (SELECT Top 1 Id FROM dbo.PageElement WHERE TypeId = 4 and id not in( SELECT Top 1 Id FROM dbo.PageElement WHERE TypeId = 4))
SET @ITEM3 = (SELECT Top 1 Id FROM dbo.PageElement WHERE TypeId = 4 and id not in( SELECT Top 2 Id FROM dbo.PageElement WHERE TypeId = 4))
SET @ITEM4 = (SELECT Top 1 Id FROM dbo.PageElement WHERE TypeId = 4 and id not in( SELECT Top 3 Id FROM dbo.PageElement WHERE TypeId = 4))
SET @ITEM5 = (SELECT Top 1 Id FROM dbo.PageElement WHERE TypeId = 4 and id not in( SELECT Top 4 Id FROM dbo.PageElement WHERE TypeId = 4))

答案 2 :(得分:0)

使用SELECT TOP 5

SELECT TOP 5 Id FROM dbo.PageElement
WHERE TypeId = 4
ORDER BY NEWID() -- Optional if you want them randomised