简体   繁体   English

带有动态参数的 SQL 查询

[英]SQL query with dynamic parameters

I tried to get some data from DB.我试图从数据库中获取一些数据。 I need get account information from my table - this type of information will depend on User.我需要从我的表中获取帐户信息 - 这种类型的信息将取决于用户。 If he/she will insert account type = 1 -> he will get this information.如果他/她将插入帐户类型= 1 -> 他将获得此信息。 How could I create query if it will depend on user: for example user could choose one or more account types and how would show my query?如果查询取决于用户,我如何创建查询:例如,用户可以选择一种或多种帐户类型以及如何显示我的查询? Now I have something like:现在我有类似的东西:

SELECT accountID, accountName,AccountNo,accountType from account_ref
where accountType not in (4, 9) and accountType IN (1, 2, 3)

But account type could be one or not.但是帐户类型可以是一种也可以不是。

EDITED: Okey, If I try to set this property from my program (it is c#) In this case I created method: input parameters - it is list with AccountType(Which user turned) How could I set it dynamically编辑:Okey,如果我尝试从我的程序(它是 c#)设置这个属性在这种情况下我创建了方法:输入参数 - 它是 AccountType 列表(哪个用户打开)我怎么能动态设置它

        public async Task<IList<AccountInfo>> GetAccountByAccountType(IList<AccountType> item)
        {
            //item

            string query = $"SELECT accountID, accountName, AccountNo, accountType from account_ref " +
                            "where accountType not in (4, 9) and accountType IN(1, 2, 3)";

            var accType = await Connection.QueryAsync<AccountInfo>(query);

            return accType.ToList();
        }

You can use IN with comma sepearted values您可以将 IN 与逗号分隔值一起使用

DECLARE @ids NVARCHAR(100) ='1,2,3'    
SELECT accountID, accountName,AccountNo,accountType 
FROM account_ref
WHERE accountType NOT IN (4, 9) 
AND accountType IN (SELECT value from STRING_SPLIT (@ids, ',')) 

As per your comments, create a temporary table @AccountType or temp variable and then store the values in it which are getting passed dynamically and then use it like this.根据您的评论,创建一个临时表 @AccountType 或临时变量,然后将动态传递的值存储在其中,然后像这样使用它。

INSERT INTO @AccountType
SELECT Value FROM dbo.FncSplitArrayIntoTable(@accountTypeParameter, ',')

SELECT accountID, accountName, AccountNo, accountType 
FROM account_ref
WHERE accountType IN (SELECT accountType FROM @AccountType)

FncSplitArrayIntoTable : Implement a custom function to split dynamically passed parameter with comma-separated values. FncSplitArrayIntoTable :实现自定义函数以使用逗号分隔值拆分动态传递的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM