简体   繁体   中英

Concatenate column values in SQL Server

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.

My normal SQL statement:

SELECT first_name + ' ' + last_name as userName from Table

My current VB statement:

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: 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.

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

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.

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

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

Use the SPACE() function to rule out quoting inconsistencies when formatting strings in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM