用SQL语言选择符合通配符的URL的记录[英] SQL to select rows that match a URL with wildcard

本文是小编为大家收集整理的关于用SQL语言选择符合通配符的URL的记录的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我在数据库中有一个表,其中一列包含一个 URL,如 http://example.com/users/*/个人资料

我得到了一个 URL(例如 http://example.com/users/234/profile) 并希望选择 db 中与 url 匹配的所有行(在这种情况下 * 是通配符).

我正在考虑使用正则表达式来执行此操作,方法是将 * 替换为任何字符的正则表达式.但我不确定选择的 SQL 或 LINQ 代码应该是什么.

你们有什么想法吗?

推荐答案

除非我遗漏了一些明显的东西,否则这应该只需要一个简单的 LIKE 查询.

SELECT *
FROM YourTable
WHERE URL LIKE 'http://example.com/users/%/'

正则表达式在 SQL 查询中是多余的和棘手的.

注意:% 字符相当于 SQL 表达式中的 * 通配符.

如果您想使用 LINQ 并且只针对 SQL Server,您可以使用以下语法:

var results =
        from yt in YourTable
        where SqlMethods.Like(yt.URL, "http://example.com/users/%/")
        select yt;

本文地址:https://www.itbaoku.cn/post/1556802.html

问题描述

I have a table in the db with one column containing a URL like http://example.com/users/*/profile

I am given a URL (like http://example.com/users/234/profile) and want to select all the rows in the db that match the url (in this case * is a wildcard).

I was thinking of using Regex to do this, by replacing the * with regex for any character. But am unsure as to what the SQL or LINQ code should be for the selection.

Do you guys have any ideas?

推荐答案

Unless I am missing something obvious, this should just require a simple LIKE query.

SELECT *
FROM YourTable
WHERE URL LIKE 'http://example.com/users/%/'

Regex is overkill and tricky in SQL queries.

Note: The % character is the equivalent of the * wildcard in SQL expressions.

If you want to use LINQ and are only working against SQL Server, you can use this syntax:

var results =
        from yt in YourTable
        where SqlMethods.Like(yt.URL, "http://example.com/users/%/")
        select yt;