动态 SQL 语句新手

发布于 2024-09-28 00:03:38 字数 807 浏览 2 评论 0原文

我目前正在 Visual Studio 2010 中使用 C# 使用 ASP.NET Framework 在网站上制作一个非常简单的 WebApp。

该网站将连接到在我的笔记本电脑上运行的 SQL EXPRESS 服务器(全部基于本地)

我有一个定义如下的表现在

CREATE TABLE Users(
 userName varchar(50),
 email varchar(50),
 firstName varchar(50),
 lastName varchar(50),
 gender varchar(50),
 birthday date,
 age int,
 location varchar(50),
 gname varchar(50)
 PRIMARY KEY (userName, email))
GO

,我的网站上有一个名为“用户”的页面。注意:gname 表示组名称(即,用户加入一个兴趣小组。)

这里我有一个看起来像这样的表单:

UserName:
Gender:
Age:
GroupName:
Location:

现在,这意味着我有 5 个不同的字段,因此,我必须为以下内容编写 25 个 SQL 语句:每个不同的情况。我觉得这很天真。

我尝试在谷歌上搜索动态 SQL 语句,这似乎并没有解决我的问题(或者至少我不明白他们如何解决我的问题)。

谁能给我指出正确的方向来学习如何实现足够智能的 SQL 语句,以根据用户输入的哪个字段生成查询?

向那些可能认为我没有对看似相当简单的事情进行研究的人表示歉意。

-阿里

Im currently making a very simple WebApp on a Website using ASP.NET Framework using C# in Visual Studio 2010.

The website will connect to my SQL EXPRESS server running on my laptop (Its all locally based)

I have a table defined as below

CREATE TABLE Users(
 userName varchar(50),
 email varchar(50),
 firstName varchar(50),
 lastName varchar(50),
 gender varchar(50),
 birthday date,
 age int,
 location varchar(50),
 gname varchar(50)
 PRIMARY KEY (userName, email))
GO

Now, I have a page on my website called Users. NOTE: gname means Group Name (ie, users join an interest group.)

Here I have a form that looks something like this:

UserName:
Gender:
Age:
GroupName:
Location:

Now, this would mean I have 5 different fields, and hence, I would have to write 25 SQL statements for each different case. Which I find pretty naive.

I tried Googling around for Dynamic SQL Statements, which do not seem to be addressing my problem here (or at least I don't understand how they address my problem).

Can anyone point me in the right direction to learn how to implement SQL statements thats smart enough to generate queries based on which field has been given input by the user?

Apologise to anyone who might think I have not done my research to something that might seem rather simple.

-Ali

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

黒涩兲箜 2024-10-05 00:03:38

这里有很多事情是错误的。

主键(用户名、电子邮件))

废话。主键是唯一的。用户名是唯一的。您想要的是电子邮件的唯一索引(位于顶部),但不是组合主键,因为这意味着只要 2 个用户“Joe”具有不同的电子邮件地址,那么他们就是合法的。

也就是说,也许不使用电子邮件和用户名作为主键,而是使用 gi 和合成键。

同样在这里:

性别 varchar(50),

您的性别是什么? “王八蛋”?在大多数情况下,人们将其写为 CHAR(1) NULL,表示“M”或“F”或 NULL(用户未输入)。不要将解码后的字符串存储在数据库中进行统计。

继续:

年龄整数,

为什么?可以用一行代码从出生日期和当前日期计算年龄。这是维护的噩梦。人们输入自己的生日。在您的程序中使用它。不要在不维护的情况下存储变化的数据(它们会变旧)。

和:

位置 varchar(50),

现在,这没有任何意义。真的。首先,它应该是一个带有参考的表格(位置)。其次,即使您不相信,50 个字符也太小了。有些空间的名称更长。无论如何,学习数据标准化。

这:

gname varchar(50)

和这个:

注意:gname 表示组名称(即
用户加入兴趣小组。)

只有当用户只加入一个小组时才有意义,即使这样,它的设计也很糟糕——应该有一个小组表。简单的情况:表组,这将是具有该组的主(合成)键的 GroupREF。否则什么都不是,临时表将用户附加到组,因为一个用户可以是多个组的一部分。

谁能指出我的正确方向
学习如何实施的方向
SQL 语句足够智能
根据哪个字段生成查询
用户已给出输入?

是的。这就是所谓的学习编程。严重地。

  • 没有任何 SQL 语句可以真正有效地完成此操作。
  • SQL 是文本。字符串。操作字符串是基本的编程。

基本上,坐下来编写一个仅执行您需要的 SQL 语句字符串。在执行此操作之前,您可能需要阅读 SQL for DUmmies 之类的书籍,以了解有关表设计的想法。

如果你想要一个静态语句,你可以输入类似的内容
* 参数@surname for certainname - 始终使用参数来传递字段中的值。

WHERE (surname LIKE @surname OR surname IS NULL)

和 SQL Server 将以相当高效的方式处理它(因为它可以看到只有一部分可以计算为 null)。只是为了回答你的问题。

Many things wrong here.

PRIMARY KEY (userName, email))

Crap. The primary key is unique. The username is unique. What you want is a unique index on email, on top, but not a combined primary key, because it means it would be legal to have 2 users "Joe" as long as they have different email addresses.

That said, maybe not use the email and username as primary key but gi with a synthetic one.

Same here:

gender varchar(50),

What is gender in your case? "SonOfABitch"? In most cases people write that as CHAR(1) NULL, means either "M" or "F" or NULL (user has not entered). Do NOT store decoded strings in a database for stati.

Goes on:

age int,

Why? Age can be calculated in code in one line from BIrthdate and current date. This is a maintenance nightmare. People enter their birthdate. Work with it in your program. Do not store changing data (they get older) without maintaining it.

And:

location varchar(50),

Now, this makes no sense. Really. FIrst, it should be a Table (Locations) with a reference in here. Second, even if you dont beliefveiit, 50 chars are TOO SMALL. Some spaces have longer names. Anyhow, learn on data normalization.

This:

gname varchar(50)

and this:

NOTE: gname means Group Name (ie,
users join an interest group.)

ONLY makes any sense if users only ever join one group, and even then it stinks as design - there should be a group table. Easy case: Table Groups, this would be a GroupREF with the primary (synthetic) key of teh group. Otherwise it is nothing, and an interim table attaches users to groups, as a user can be part of many groups.

Can anyone point me in the right
direction to learn how to implement
SQL statements thats smart enough to
generate queries based on which field
has been given input by the user?

Yes. It is called learning programming. Seriously.

  • There is no SQL Statement that does so really efficiently.
  • SQL is text. Strings. Manipulating string is basic programming.

Basically, sit down and put up a SQL Statement string that does what you need ONLY. Before you do that you may want to read a book like SQL for DUmmies to get an idea about table design.

If you want a static statement, you can put in something like
* Paramter @surname for surename - always use parameters to pass values in your field.

WHERE (surname LIKE @surname OR surname IS NULL)

and SQL Server will handle it decently efficiency wise (as it can see only one part can either evaluate to null). Just to answer your question.

夜巴黎 2024-10-05 00:03:38

考虑@GôTô 的代码和下面的 SQL 的组合

select * 
from Users u
where   (@username is null or Username like '%'+ @username + '%')
    AND (@Gender is null or Gender = @gender)
    AND (@age is null or Age = @age)
    AND (@gname is null or gname = @gname)
    AND (@location is null or location = @location)

Consider a combination of @GôTô's code and the below SQL

select * 
from Users u
where   (@username is null or Username like '%'+ @username + '%')
    AND (@Gender is null or Gender = @gender)
    AND (@age is null or Age = @age)
    AND (@gname is null or gname = @gname)
    AND (@location is null or location = @location)
随遇而安 2024-10-05 00:03:38

在查询中使用参数,如下所示:

string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
    + "WHERE CustomerID = @ID;";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.Add("@ID", SqlDbType.Int);
    command.Parameters["@ID"].Value = customerID;

    // Use AddWithValue to assign Demographics.
    // SQL Server will implicitly convert strings into XML.
    command.Parameters.AddWithValue("@demographics", demoXml);

    try
    {
        connection.Open();
        Int32 rowsAffected = command.ExecuteNonQuery();
        Console.WriteLine("RowsAffected: {0}", rowsAffected);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

来自 http: //msdn.microsoft.com/en-gb/library/system.data.sqlclient.sqlcommand.parameters.aspx

Use parameters in your query like this:

string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
    + "WHERE CustomerID = @ID;";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.Add("@ID", SqlDbType.Int);
    command.Parameters["@ID"].Value = customerID;

    // Use AddWithValue to assign Demographics.
    // SQL Server will implicitly convert strings into XML.
    command.Parameters.AddWithValue("@demographics", demoXml);

    try
    {
        connection.Open();
        Int32 rowsAffected = command.ExecuteNonQuery();
        Console.WriteLine("RowsAffected: {0}", rowsAffected);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

From http://msdn.microsoft.com/en-gb/library/system.data.sqlclient.sqlcommand.parameters.aspx

初相遇 2024-10-05 00:03:38

您不需要使用动态sql。这是参数化查询或存储过程的解决方案:


-- assuming you have parameters @username,@gname,@pass for searching user

select * from Users
where (username like '%'+@username+'%' or @username is null)
and (gname = @gname or @gname is null)
and (password = @password or @password = null)

您可以根据需要添加任意数量的参数,并根据需要添加列名来代替 * 来开始使用

You don't need to use dynamic sql. here is your solution of parameterized query or stored procedure:


-- assuming you have parameters @username,@gname,@pass for searching user

select * from Users
where (username like '%'+@username+'%' or @username is null)
and (gname = @gname or @gname is null)
and (password = @password or @password = null)

you can add as many params as you want and add column names as you want in place of * to get starte with

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文