LIKE语句中的参数仅返回精确值

时间:2017-11-15 23:02:51

标签: sql sql-server

我有一个如下所示的参数化查询,它应该返回有关参数名称的项目的信息。但是,它仅适用于完全匹配

 {
    try {
        File file = new File("input.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        ArrayList<String> txtline = new ArrayList<String>();
        while ((line = bufferedReader.readLine()) != null) {
            txtline.add(line);
            System.out.println(txtline);
        }

        fileReader.close();
        System.out.println(stringBuffer.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

由于'bananas'在数据库中,它会返回该信息。如果它放'banan',它什么也不返回。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您还可以将通配符放在WHERE子句中:

BEGIN
    SET NOCOUNT ON;

    DECLARE @name VARCHAR(50) = 'bananas';

    SELECT  category ,
            SUM(netweight) AS NetWeight
    FROM    PieChart
    WHERE   [name] LIKE '%' + @name + '%'
    GROUP BY category ,
            [name]
END

答案 1 :(得分:0)

你需要通配符。此外,您应该使用where,而不是having。所以:

BEGIN
    SET NOCOUNT ON

    DECLARE @name varchar(50);

    SET @name = 'banan%';

    SELECT category, sum(netweight) AS NetWeight 
    FROM PieChart
    WHERE name LIKE @name
    GROUP BY category, name; 
END;