2016-08-12 179 views
0

我在我的數據庫表中有另一個名爲FileName的字段,我希望通過FileName選擇記錄。我應該添加什麼代碼。SQL存儲過程選擇語句

ALTER PROCEDURE [dbo].[spx_Pager] 
@PageNo int = 1, 
@ItemsPerPage int = 2, 
@TotalRows int out, 
@f_name nvarchar(50) 

AS 
BEGIN 
SET NOCOUNT ON 
DECLARE 
@StartIdx int, 
@SQL nvarchar(max), 
@SQL_Conditions nvarchar(max), 
@EndIdx int 

IF @PageNo < 1 SET @PageNo = 1 
IF @ItemsPerPage < 1 SET @ItemsPerPage = 10 

SET @StartIdx = (@PageNo -1) * @ItemsPerPage + 1 
SET @EndIdx = (@StartIdx + @ItemsPerPage) - 1 
SET @f_name = (@f_name) 
SET @SQL = 'SELECT FilePath 
      FROM (
      SELECT ROW_NUMBER() OVER(ORDER BY ID) AS Row, * 
        FROM tblFiles) AS tbl WHERE Row >= ' 
        + CONVERT(varchar(9), @StartIdx) + ' AND 
        Row <= ' + CONVERT(varchar(9), @EndIdx) 
EXEC sp_executesql @SQL 

SET @SQL = 'SELECT @TotalRows=COUNT(*) FROM tblFiles' 
EXEC sp_executesql 
    @query = @SQL, 
    @params = N'@TotalRows INT OUTPUT', 
    @TotalRows = @TotalRows OUTPUT 
END 
+1

你爲什麼要用動態sql? –

+0

在哪個表中的另一個字段?你需要詳細說明這一點。 – scsimon

+0

同一張表「tblFiles」 – user2970635

回答

0

你沒有給我太多的繼續。但這是你需要的嗎?

ALTER PROCEDURE [dbo].[spx_Pager] 
@PageNo int = 1, 
@ItemsPerPage int = 2, 
@TotalRows int out, 
@f_name nvarchar(50) 

AS 
BEGIN 
SET NOCOUNT ON 
DECLARE 
@StartIdx int, 
@SQL nvarchar(max), 
@SQL_Conditions nvarchar(max), 
@EndIdx int 

IF @PageNo < 1 SET @PageNo = 1 
IF @ItemsPerPage < 1 SET @ItemsPerPage = 10 

SET @StartIdx = (@PageNo -1) * @ItemsPerPage + 1 
SET @EndIdx = (@StartIdx + @ItemsPerPage) - 1 
SET @f_name = (@f_name) 
SET @SQL = 'SELECT FilePath 
     FROM (
     SELECT ROW_NUMBER() OVER(ORDER BY ID) AS Row, * 
       FROM tblFiles) AS tbl WHERE Row >= ' 
       + CONVERT(varchar(9), @StartIdx) + ' AND 
       Row <= ' + CONVERT(varchar(9), @EndIdx) + ' AND 
       FileName = @file_name' 
EXEC sp_executesql @SQL 

SET @SQL = 'SELECT @TotalRows=COUNT(*) FROM tblFiles' 
EXEC sp_executesql 
    @query = @SQL, 
    @params = N'@TotalRows INT OUTPUT', 
    @TotalRows = @TotalRows OUTPUT, 
    @file_name = @f_name 
END 
+0

我試過上面的代碼,但我得到的錯誤是必須聲明標量變量「f_name」 – user2970635

+0

我更新了我的答案。我認爲你遇到的問題是如何在動態SQL中使用參數。如果我的回答不起作用,請檢查此鏈接,它應該有所幫助。 http://www.aspsnippets.com/Articles/How-to-use-and-pass-parameters-to-dynamic-SQL-in-SQL-Server.aspx。 –