Nerdtron
Nerdtron

Reputation: 1516

String concatenation not working as expected in SELECT statement

I'm using MS Access to work with an SQL Server database through an ODBC connection on Windows 7.

The ultimate goal is to append a string literal to one of the fields for a subset of rows. Initially, though, I'm just trying to do a SELECT so I can make sure I have everything correct. I'm having trouble trying to append a string literal to the field.

The below simple SQL works well.

SELECT Name FROM Customers WHERE CustomerType = 1;

Next step was to try and modify the displayed name slightly.

SELECT Name, 'PREFIX' & Name FROM Customers WHERE CustomerType = 1;

The above also worked. Then I tried the following.

SELECT Name, Name & 'SUFFIX' FROM Customers WHERE CustomerType = 1;

This does not work. The output shows just the Name field with nothing appended. I looked around and found SQL Server seems to support CONCATENATE('a' + 'b'). I tried using that in the query but it failed with an error from Access about there not being a CONCATENATE function.

I also tried double quotes instead and + instead of &.

Seems odd that the prefix case worked and the suffix case did not.

The eventual goal, again, would be to construct something like the below.

UPDATE Customers SET Name = Name & 'SUFFIX' WHERE CustomerType = 1;

This would append a suffx to a text field for a subset of rows in the table.

Any ideas?

Upvotes: 1

Views: 3588

Answers (2)

HansUp
HansUp

Reputation: 97101

My impression is you have an Access query with Customers as an ODBC link to a SQL Server table. If that is correct, either of these 2 query versions should work.

SELECT
    [Name],
    [Name] & 'SUFFIX'
FROM Customers
WHERE CustomerType = 1;

SELECT
    c.Name,
    c.Name & 'SUFFIX'
FROM Customers AS c
WHERE c.CustomerType = 1;

The reason for this suggestion is that Name is a reserved word. One thing that makes reserved words frustrating is that you don't know when they will bite you. A reserved word might not cause trouble in one context but cause the same SQL statement to fail in another context. Enclosing the name in square brackets or qualifying the name with an alias (or the table name) avoids confusing Access' db engine.

Try this for your UPDATE.

UPDATE Customers
SET [Name] = [Name] & 'SUFFIX'
WHERE CustomerType = 1;

Upvotes: 2

podiluska
podiluska

Reputation: 51494

In SQL Server, & is for binary masks. You want the + operator

UPDATE Customers 
SET Name = Name + 'SUFFIX' 
WHERE CustomerType = 1;

I don't know where you got CONCATENATE from - There is a CONCAT function in SQL 2012, but nothing like that in any other version

Upvotes: 4

Related Questions