2011-05-16 166 views
0

我正在嘗試使用SP獲取值。查詢如下。SQL查詢未獲取值

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 @[email protected]+' Join Tbl_Orders c ON c.UserID = '+convert(varchar(10),@UserID)+'' 

set @[email protected]+'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確實幫助我獲得價值。

在此先感謝。

回答

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 
+0

+1。它有時比第一次看起來更棘手 – 2011-05-16 14:02:55

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);

+0

感謝您對我的reply.In查詢我需要補充一些條件這個字符串。如果這是執行我會添加後 – user755716 2011-05-16 13:51:05

+1

+1; 'SectionsViewed'也很奇怪;它將永遠是'''' – 2011-05-16 13:52:12

+1

是的,請張貼條件。我很好奇,如果我們可以添加該條件而不必將查詢放入字符串變量中。儘量避免這種情況:) – 2011-05-16 13:52:46

0

你的最後一句話是選擇數據到臨時表,而不是正在被返回的結果集。如果你添加以下到你的過程結束時,你應該把你的數據:

select * from #myCourses1 
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