简体   繁体   中英

How to use list in WHERE IN in SQL code in Power bi?

I am trying to load a fraction of a table from SQL database in Power BI using SQL language. I want to use WHERE IN and apply a variable list of values for filtering (this helps to reduce loading time). Since the list is changing, I do not want to write the filter values to the formula.

I tried this formula:

Source = Sql.Database("server", "database", [Query="SELECT header FROM report WHERE header IN ("&List&")"])

I get an error message about Text and List mismatch:

Expression.Error: We cannot apply operator & to types Text and List.

This works, but requires direct typing the filtering values in the formula:

Source = Sql.Database("server", "database", [Query="SELECT header FROM report WHERE header IN ('Item1', 'Item2')"])

How can the list be transformed to text? What would be the correct syntax? Is that even possible?

You can use Text.Combine to transform your list to comma separated string of values. So your code will look like this:

Source = Sql.Database("server", "database", [Query="SELECT header FROM report WHERE header IN (" & Text.Combine(List, ",") & ")"])

If you need to quote the list values, try this way (but note my comment bellow!):

Source = Sql.Database("server", "database", [Query="SELECT header FROM report WHERE header IN ('" & Text.Combine(List, "','") & "')"])

Note, you don't need to embed SQL queries for this behavior. If you just load the table normally through the GUI editor and apply a filter to a column, that filter will be "folded" back to the SQL database engine for evaluation. "Folding" is the name for a piece of technology in Power Query/M where an M query can be translated into the language of the data source, so that eg filtering operations are performed in your SQL database, rather than in Power Query. You can always check what query is being generated for SQL sources by right-clicking on an applied step and selecting View Native Query .

If you really need to interpolate a list into a string, @AndreyNikolov's answer is the path to take.

Source = Sql.Database("server", "database", [Query="SELECT header FROM report WHERE header IN (" & Text.Combine(List, ",") & ")"])

Is List a text file stored somewhere?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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