Asp.net
按 IN 子句對 SQL Server 結果排序
我有一個使用 IN 子句的儲存過程。在我的 ASP.NET 應用程序中,我有一個為儲存過程提供值的多行文本框。我希望能夠按在文本框中輸入的值進行排序。我發現瞭如何在 mySQL 中輕鬆做到這一點(使用 FIELD 函式),但不是 SQL Server 等價物。
所以我的查詢看起來像:
Select * from myTable where item in @item所以我會從我的應用程序中傳遞值,比如'113113’、‘112112’、‘114114’(以任意順序)。我想按該列表對結果進行排序。
CASE 陳述是否可行?我不知道文本框數據中有多少項目。
你是如何參數化
IN子句的?正如您在 SQL Server 2008 上一樣,我將傳入一個包含兩列的表值參數
item,sort_order然後加入該參數。然後你可以ORDER BY sort_order在最後添加一個。
從上面KM的評論…
我知道你沒有說它是逗號分隔的,但如果它是 CSV 或者即使你有空格分隔,你也可以執行以下操作。
DECLARE @SomeTest varchar(100) --used to hold your values SET @SomeTest = (SELECT '68,72,103') --just some test data SELECT LoginID --change to your column names FROM Login --change to your source table name INNER JOIN ( SELECT * FROM fn_IntegerInList(@SomeTest) ) n ON n.InListID = Login.LoginID ORDER BY n.SortOrder然後創建
fn_IntegerInList():CREATE FUNCTION [dbo].[fn_IntegerInList] (@InListString ntext) RETURNS @tblINList TABLE (InListID int, SortOrder int) AS BEGIN declare @length int declare @startpos int declare @ctr int declare @val nvarchar(50) declare @subs nvarchar(50) declare @sort int set @sort=1 set @startpos = 1 set @ctr = 1 select @length = datalength(@InListString) while (@ctr <= @length) begin select @val = substring(@InListString,@ctr,1) if @val = N',' begin select @subs = substring(@InListString,@startpos,@ctr-@startpos) insert into @tblINList values (@subs, @sort) set @startpos = @ctr+1 end if @ctr = @length begin select @subs = substring(@InListString,@startpos,@ctr-@startpos) insert into @tblINList values (@subs, @sort) end set @ctr = @ctr +1 set @sort = @sort + 1 end RETURN END這樣,您的函式將創建一個包含排序順序的表,
SortOrder以及您傳入的 ID 或編號。您當然可以修改它以便尋找空間rather then,values. Otherwise Martin has the right idea in his answer. Please note in my example I am using one of my tables, so you will need to change the nameLoginto whatever you are dealing with.