使用 like 或任何 SQL 查询在 C# 值和 SQL 记录之间进行查找
本文关键字:SQL 之间 记录 查找 值和 like 任何 查询 使用 | 更新日期: 2023-09-27 18:36:22
嗨,我有一个标签来获取这种格式的数字:
0123-480-1234
这是一个完整的电话号码,包括城市代码和区号。
我在SQ L服务器中有一个用于区号数据库的表。SQ L 表:区号
代码区 480 = 1580 = 2
我想要的只是当标签 1 获得完整格式的数字时,查找其区域并将其设置为标签 2。
更新2:从SQL表中查找此号码(0123-480-1234)的区号并将其放入Label2中
标签1= 0123-480-1234 标签2=?????
更新 3:标签 2 的值为 480,但我如何将其值与 SQL 区号表进行比较?
string a = label2.Txt
SqlCommand cmd = new SqlCommand("select area from dbo.areacodes where code=@code", cnt);
cnt.Open();
cmd.Parameters.AddWithValue("@code", a);
SqlDataReader re = cmd.ExecuteReader();
while (re.Read())
MessageBox.Show(re["area"].ToString());
cnt.Close();
更新 4 问题已修复:
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=db3;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("select count (number) from t2 where number=@number", conn); // select and count number
cmd.Parameters.AddWithValue("@number", label1.Text); //c# source
label5.Text=(cmd.ExecuteScalar().ToString()); //show count
conn.Close();
源 :想要将文本框中输入的文本与 SQL 列进行比较,并从该行中提取其他值(如果值与使用 C# 匹配 asp.net
很多想象力在不知道真正需求的情况下投入了什么,但这样的东西应该在纯SQL中工作。
-- Some preparation for testing ...
IF OBJECT_ID('AreaCode', 'U') IS NOT NULL
DROP TABLE AreaCode
GO
CREATE TABLE AreaCode
(
Code INT NOT NULL,
Area INT NOT NULL
)
GO
INSERT INTO AreaCode VALUES
(480, 3),
(580, 2)
GO
-- This is the label you want to check.
DECLARE @LabelForLookUp CHAR(13) = '0123-480-1234'
--Use LIKE to extract its valid code if it matches the strict format.
DECLARE @Code INT = NULL
IF(@LabelForLookUp LIKE '[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')
SET @Code = CAST(SUBSTRING(@LabelForLookUp, 6, 3) AS INT)
--This is the area that we will look up in our table.
DECLARE @Area INT = NULL
SELECT @Area = Area
FROM AreaCode
WHERE Code = @Code
-- This variable is null if area was not found, else it is the area we want.
PRINT @Area
编辑:
如果可以控制 C# 中的@LabelForLookUp,请使用 C# 对其进行筛选,如其他答案中所述。
要从像nnn-nnn-nnnnnn这样的字符串中获取区号,您可以使用以下sql
DECLARE @Var VARCHAR(20) = '0123-480-1234'
SELECT PARSENAME(REPLACE(@Var, '-','.'),2)
Result: 480
由于它是设置为标签的值,因此您可以执行以下操作以从标签中获取它
string input = LabelControl1.Text.ToString();
string areaCode = input.Split(new char[] { '-', '-' })[1];
现在,您可以使用此区号值从面积表中获取区域编号。