2015-06-07 54 views
-1
DELIMITER // 

CREATE PROCEDURE SearchProduct(

    IN Search VARCHAR(1000), 
    IN OrderBy Varchar(100), 
    In FromId varchar(10), 
    In ToId varchar(10) 

    ) 

BEGIN 

Set @MQuery= ' 
with DataTable as (

    SELECT Product.Id as ProductId, 
      Category.Id as CategoryId, 
      Product.Active, 
      Product.Name as ProductName, 
      Catgeory.Name as CategoryName, 
      Product.AddedOn, 
      Product.AddedBy as UserId, 
      ROW_NUMBER() OVER (Order by '+ OrderBy +') RowNumber, 
    Count(*) OVER() as TotalRecords 

    FROM Product 
    inner join ProductCategory 
    on Product.Id=ProductCategory.ProductId 
    inner join Category 
    on Category.Id= ProductCategory.CategoryId 

WHERE ' + Search+ ') '+ 

' 
Select DataTable.*, (User.FirstName+space(1) + User.LastName) as FullName 

from DataTable 
inner join User on DataTable.UserId= User.Id 
where DataTable.RownNumber berween '+FromId +' and '+ ToId 
+ ' order by DataTable.RowNumber' 

execute @MQuery; 

END // 

DELIMITER ; 

結果:MySQL存儲過程沒有編譯以下錯誤

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'execute @MQuery;

END' at line 17

+0

在DataTable.RowNumber命令後面可能需要一個';'分隔符來終止'SET'語句。 –

+0

你正在使用CTE,所以它不會在MySQL上工作。也許你的意思是SQL服務器? – Mihai

+0

確定..其實我一般在Sql服務器上使用這個存儲過程,但是現在我在mysql上工作,所以需要在Mysql – Jimmy

回答

0

來連接MySQL中字符串的正確方法是使用功能concat()。執行它們的正確方法是使用prepare/exec

而且,在MySQL中沒有with語句。你試圖寫的陳述是這樣的:

Set @MQuery = concat(' 
with DataTable as (

    SELECT Product.Id as ProductId, 
      Category.Id as CategoryId, 
      Product.Active, 
      Product.Name as ProductName, 
      Catgeory.Name as CategoryName, 
      Product.AddedOn, 
      Product.AddedBy as UserId, 
      ROW_NUMBER() OVER (Order by '+ OrderBy +') RowNumber, 
    Count(*) OVER() as TotalRecords 

    FROM Product 
    inner join ProductCategory 
    on Product.Id=ProductCategory.ProductId 
    inner join Category 
    on Category.Id= ProductCategory.CategoryId 

WHERE ', Search, ') ', 
' 
Select DataTable.*, concat(User.FirstName, ' ', User.LastName) as FullName 

from DataTable 
inner join User on DataTable.UserId= User.Id 
where DataTable.RownNumber berween ', FromId, ' and ', ToId, 
' order by DataTable.RowNumber'); 

prepare stmt from @MQuery; 

exec stmt; 

這可能會編譯,但你會有其他問題。您需要重構MySQL的查詢。顯然,在編寫存儲過程之前,您沒有嘗試先運行查詢。這就像賭博,並把所有的錢放在你玩的第一場比賽上。它可能有效,但不太可能。

它看起來像你混合MySQL和SQL Server語法。

+0

中使用類似的查詢類型......但是你能幫我轉換爲Mysql – Jimmy

+0

@ParulBansal。 。 。我建議你單獨和明確地提出這個問題作爲一個問題(並省略存儲過程的東西)。只是讓查詢工作。一個SQL小提琴會對這樣一個問題很有幫助。 –