连接SQL Server中的列值

时间:2022-01-05 09:36:12

I want to select two columns (first and last name) from a database, combine them into one, and stick them into a data set to be displayed in a datagrid. I also need to add a space between them for formatting.

我想从数据库中选择两个列(第一个和最后一个),将它们合并为一个列,并将它们插入到一个数据集中,在datagrid中显示。我还需要在它们之间添加一个空间用于格式化。

My normal SQL statement:

我的正常的SQL语句:

SELECT first_name + ' ' + last_name as userName from Table

My current VB statement:

我现在的VB声明:

strSQL = "SELECT first_name + ' ' + last_name as userName from Table"

When I attempt to do this, my application throws the following error: System.Data.SqlClient.SqlException: An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Add a name or single space as the alias name.

当我尝试这样做时,我的应用程序会抛出以下错误:System.Data.SqlClient。SqlException:对象或列名丢失或为空。对于SELECT INTO语句,请验证每个列都有一个名称。对于其他语句,请查找空别名名称。定义为“”或[]的别名是不允许的。添加一个名称或一个空格作为别名。

EDIT: For those asking about the database and/or if this is the correct query, if I format my VB query as follows:

编辑:对于询问数据库和/或如果这是正确的查询,如果我将VB查询格式化如下:

strSQL = "SELECT first_name + last_name as userName from Table"

I get the proper results, but then the column looks like FirstLast and is very difficult to read.

我得到了正确的结果,但是这个列看起来像FirstLast,而且很难读。

I'm guessing there's something small I'm missing on how to do this properly within VB. Can anyone advise?

我猜我在VB中缺少了一些小技巧。谁能建议?

Things I've tried:

我试过的东西:

strSQL = "Name = TU1.first_name + ' ' + TU1.last_name"

This throws the same error. However...

这会抛出相同的错误。然而……

strSQL = "Name = TU1.first_name + '' + TU1.last_name"

gives me a result of First'Last

给我一个第一和最后的结果

1 个解决方案

#1


3  

Use the SPACE() function to rule out quoting inconsistencies when formatting strings in SQL:

使用SPACE()函数排除在SQL中格式化字符串时引用不一致的情况:

strSQL = "SELECT first_name + SPACE(1) + last_name as userName from Table"

That being said, this type of formatting is best left to the presentation, not data layer.

也就是说,这种格式最好留给表示,而不是数据层。

#1


3  

Use the SPACE() function to rule out quoting inconsistencies when formatting strings in SQL:

使用SPACE()函数排除在SQL中格式化字符串时引用不一致的情况:

strSQL = "SELECT first_name + SPACE(1) + last_name as userName from Table"

That being said, this type of formatting is best left to the presentation, not data layer.

也就是说,这种格式最好留给表示,而不是数据层。