计算SQL Server数据库表中表中单词的出现次数

时间:2015-12-19 09:45:41

标签: sql sql-server vb.net

我需要计算列news1中SQL Server表title中单词的出现次数。

代码返回零值:

sql = "SELECT SUM((LEN(title) - LEN(REPLACE(title, '" & TextBox1.Text.Trim & "', '')))/LEN('" & TextBox1.Text.Trim & "')) FROM news1"
comm = New SqlCommand(sql, conn)
conn.Open()
Dim count21 As Integer = comm.ExecuteScalar()
conn.Close()
MsgBox (count21)

1 个答案:

答案 0 :(得分:1)

要计算字符串中字符的出现,查询应该类似于

Len('sttring') - Len(Replace('sttring', 't', '')) -- Result : 2

所以你的查询应该是

SELECT Sum(( Len(title) - Len(Replace(title, '" & TextBox1.Text.Trim & "', ''))) / 
                  Cast(Len('" & TextBox1.Text.Trim & "') AS NUMERIC(10, 1))) 
FROM   news1 

要避免整数除法,请将分子或分母转换为十进制值。

SELECT Sum(( Len(title) - Len(Replace(title, '" & TextBox1.Text.Trim & "', '')) ) / cast(Len('" & TextBox1.Text.Trim & "') as numeric(10,1))
FROM   news1 

此外,您获得0的原因是整数除法,在您的情况下不需要

示例:

考虑(LEN(title) - LEN(REPLACE(title, '" & TextBox1.Text.Trim & "', '')))返回3LEN('" & TextBox1.Text.Trim & "'))返回10然后

select 3/10 -- Result 0