我有这样的sql语句。我将参数从代码传递给查询,如(工资,年龄)
DECLARE @salary NVARCHAR(200);
SET @salary = ?;
DECLARE @age NVARCHAR(30);
SET @age = ?;
SELECT * FROM user WHERE age=@age AND salary >=@salary;
我想把年龄作为一个数组,所以我可以像这样运行语句
SELECT * FROM user WHERE age IN someAgeArray AND salary >=@salary
我怎么能做到这一点?找不到合适的例子。
答案 0 :(得分:0)
您可以先创建一个函数,然后参阅SQL User Defined Function to Parse a Delimited String。然后你可以做这样的事情:
DECLARE @salary NVARCHAR(200);
SET @salary = ?;
DECLARE @ageList NVARCHAR(200);
SET @ageList = ?;
SELECT * FROM user WHERE age In (SELECT Int_Value FROM fnParseString(@ageList, ',') WHERE Isnumeric(Int_Value) = 1)
AND salary >=@salary;
答案 1 :(得分:0)
您好,您可以使用拆分功能,然后像这样使用。
直接数组值不用作“IN”运算符。它给出了语法错误。如果数组以逗号分隔,那么有一件事要用作
请运行查询并阅读评论。还有一些地方取消注释代码以理解逻辑。
BEGIN
tran
--first option which not give answer as direct query
declare @t table (id int, name varchar(50))
insert into @t values(1,'abc'),(2,'def'),(3,'ghi')
declare @arrayValue varchar(50) = '1,2'
--set @arrayValue = '''' + replace(@arrayValue ,',', ''',''') + ''''
--select @arrayValue
select * from @t where name in ( @arrayValue)
--second option which is dynamic query and give result. Only select portion you will add in dynamic query, this is example.
declare @sqlQuery nVarchar(max)
set @sqlQuery = '
declare @t table (id int, name varchar(50))
insert into @t values(1,''abc''),(2,''def''),(3,''ghi'')
select id as ''2ndid'', name as ''2ndname'' from @t where id in ( ' +@arrayValue + ')'
EXEC sp_executesql @sqlquery
--third option
create table t(id int, name varchar(50))
insert into t values(1,'abc'),(2,'def'),(3,'ghi')
--select * from t where id in ( @arrayValue)
set @sqlQuery = 'select id as ''3rdid'', name as ''3rdname'' from t where id in ( ' + cast ( @arrayValue as nvarchar(500))+ ')'
EXEC sp_executesql @sqlquery
rollback