我正在尝试使用SP获取值。查询如下。
create proc [dbo].[GetOrdersByUserID11]
(
@UserID int
)
as
begin
declare @status varchar(1000)
set @status=' select a.*, b.CategoryText, Cast('''' as Varchar(10)) as SectionsViewed, PurchasedDate as dateadded into #myCourses1 from dbo.Tbl_CourseInformations a JOIN Tbl_Categories b ON a.AssignCategory = b.CategoryID '
set @status=@status+' Join Tbl_Orders c ON c.UserID = '+convert(varchar(10),@UserID)+''
set @status=@status+'Order By CategoryText, CourseTitle '
print @status
exec(@status)
select * from #myCourses1
end
This is message from my query when run my SP[[dbo].[GetOrdersByUserID11] 5085 ]:
select a.*, b.CategoryText, Cast('' as Varchar(10)) as SectionsViewed, PurchasedDate as dateadded into #myCourses1 from dbo.Tbl_CourseInformations a JOIN Tbl_Categories b ON a.AssignCategory = b.CategoryID Join Tbl_Orders c ON c.UserID = 5085
(99 row(s) affected)
我收到消息99行受影响但在我的结果中只获得了带有0(零)列的标题。
Plz帮助我获得价值。
提前致谢。
答案 0 :(得分:2)
您创建的临时表仅在EXEC语句的范围内,而不是外部查询。
exec('select 1 as f into #t')
select * from #t' <-- out of scope
在声明中选择:
exec('select 1 as f into #t; select * from #t')
或者首先创建临时表(因此创建/选择在同一范围内)。
select 1 as f into #t where 0=1 --force empty
exec('insert #t values (2)')
select * from #t
答案 1 :(得分:0)
我真的不明白为什么你先把查询放在一个字符串变量中。下面的查询是否满足您的需求?
create proc [dbo].[GetOrdersByUserID11]
(
@UserID int
)
AS
BEGIN
SELECT a.*, b.CategoryText, Cast("" as Varchar(10)) as SectionsViewed,
PurchasedDate as dateadded
FROM dbo.Tbl_CourseInformations a
JOIN Tbl_Categories b ON a.AssignCategory = b.CategoryID
JOIN Tbl_Orders c ON c.UserID = convert(varchar(10),@UserID)
ORDER By CategoryText, CourseTitle
END
调用存储过程:
EXEC GetOrdersByUserID11(1234);
答案 2 :(得分:0)
您的上一条语句是将数据选择到临时表而不是正在返回的结果集中。如果您在程序结束时添加以下内容,则应获取数据:
select * from #myCourses1
答案 3 :(得分:0)
为什么要在商店流程中构建select请求?据我了解您的要求,您只需要结果。在这种情况下,最好在调用中使用带参数的视图。
CREATE VIEW [dbo].[GetOrdersByUserID11]
AS
SELECT a.*, b.CategoryText, Cast('' as Varchar(10)) as SectionsViewed, PurchasedDate as dateadded into #myCourses1 from dbo.Tbl_CourseInformations a JOIN Tbl_Categories b ON a.AssignCategory = b.CategoryID
GO
你这样称呼它:
SELECT * FROM GetOrdersByUserID11 Join Tbl_Orders c WHERE c.UserID = 5085