如何参数化包含IN具有可变数量参数的子句的查询,比如这个?
SELECT * FROM Tags
WHERE Name IN ('ruby','rails','scruffy','rubyonrails')
ORDER BY Count DESC
Run Code Online (Sandbox Code Playgroud)
在此查询中,参数的数量可以是1到5之间的任何值.
我不希望为此(或XML)使用专用存储过程,但如果有一些特定于SQL Server 2008的优雅方式,我对此持开放态度.
是否有一种优雅的方法来处理将id列表作为参数传递给存储过程?
例如,我希望我的存储过程返回的部门1,2,5,7,20.在过去,我已经通过逗号分隔的id列表,如下面的代码,但感觉真的很脏.
我认为SQL Server 2005是我唯一适用的限制.
create procedure getDepartments
@DepartmentIds varchar(max)
as
declare @Sql varchar(max)
select @Sql = 'select [Name] from Department where DepartmentId in (' + @DepartmentIds + ')'
exec(@Sql)
Run Code Online (Sandbox Code Playgroud) 我有以下代码,问题是我的变量列表@LocationList本质上是一个csv字符串.当我使用它作为(@LocationList)中LocationID的一部分时,它表示它不是一个int(LocationID是一个int).如何让这个csv字符串被teh in子句接受?
Declare @LocationList varchar(1000)
Set @LocationList = '1,32'
select Locations from table where Where LocationID in (@LocationList)
Run Code Online (Sandbox Code Playgroud) 问题:
Ajax建议 - 在食谱中搜索[ n ]成分.那就是:匹配多种成分的配方.
例如:SELECT Recipes using "flower", "salt"会产生:"Pizza", "Bread", "Saltwater"等等.
表:
Ingredients [
IngredientsID INT [PK],
IngredientsName VARCHAR
]
Recipes [
RecipesID INT [PK],
RecipesName VARCHAR
]
IngredientsRecipes [
IngredientsRecipesID INT [PK],
IngredientsID INT,
RecipesID INT
]
Run Code Online (Sandbox Code Playgroud)
查询:
SELECT
Recipes.RecipesID,
Recipes.RecipesName,
Ingredients.IngredientsID,
Ingredients.IngredientsName
FROM
IngredientsRecipes
INNER JOIN Ingredients
ON IngredientsRecipes.IngredientsID = Ingredients.IngredientsID
INNER JOIN Recipes
ON IngredientsRecipes.RecipesID = Recipes.RecipesID
WHERE
Ingredients.IngredientsName IN ('salt', 'water', 'flower')
Run Code Online (Sandbox Code Playgroud)
我目前正在使用ASP.NET C#构建我的查询,因为该WHERE子句具有动态特性.
我咬了一下,我必须在我的代码层中构建查询,而不是使用存储过程/纯SQL,理论上应该更快.
你有没有想过如何将我的代码层中的所有逻辑移动到纯SQL,或者至少我如何优化我正在做的事情的性能?
我正在考虑临时表:
第一步 …
我需要在两个不同的表上搜索偶然的整数集:
SELECT
col_1, col_2
FROM
LIKES_NUMBERS
WHERE
col_1 IN (1,2,3,5,7,1021,10041411)
SELECT
col_one, col_two
FROM
LIKES_NAMES
WHERE
col_one IN (1,2,3,5,7,1021,10041411)
Run Code Online (Sandbox Code Playgroud)
是否有可以传递给IN的SQL列表类型,以便我不重复自己?例如
DECLARE @stuff UNOBTAINIUM(1,2,3,5,7,1021,10041411)
-- ...
WHERE col_1 IN (@stuff)
-- ...
WHERE col_one IN (@stuff)
Run Code Online (Sandbox Code Playgroud)
想到创建一个临时表,但这看起来很残酷.