我需要计算列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)
答案 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 & "', '')))
返回3
和LEN('" & TextBox1.Text.Trim & "'))
返回10
然后
select 3/10 -- Result 0