Question

Basically, the subject. I'm accessing a database via Web interface, which submits SQL queries using a Web form. The database is in read-only mode, so I cannot use UPDATE statement. Also, please note that I need to act on all fields at once. Here's what I've tried:

SELECT *, REPLACE((SELECT * FROM sf0314.groups), ':', ';')
FROM sf0314.groups
WHERE group_id < 1000

Server replied with the following error message:

There was an error in your query: subquery must return only one column

I also tried to use AS to refer to all fields in the main SELECT, but it was unsuccessful as well. I understand how I can use REPLACE to update one or several named fields in the result set. But, the question is:

How can I refer to multiple (all) fields in the REPLACE statement? Thank you!

Was it helpful?

Solution

You can not. REPLACE() function accepts three string arguments, but can't accept lists or resultsets. You have to list all of your columns in the select statement, then add REPLACE function to each column.

Example

SELECT
    REPLACE(field1, ':', ';') AS field1
    REPLACE(field2, ':', ';') AS field2,
    REPLACE(field3, ':', ';') AS field3,
    REPLACE(field4, ':', ';') AS field4,
FROM
    YourTable

EDIT (Summarizing the conversation in the comments)

You can generate your field list using the metadata storage provided by the RDBMS. In most Database Engines, the INFORMATION_SCHEMA contains the metadata:

Example for MySQL:

SELECT
    CONCAT('REPLACE(`', C.COLUMN_NAME, '`, '':'', '';'')')
FROM
    information_schema.COLUMNS C
WHERE
    C.TABLE_SCHEMA = '[YourDatabaseName]'
    AND C.TABLE_NAME = '[YourTableName]'

Example for MSSQL (using DMVs):

USE [YourDatabaseName];

SELECT
    'REPLACE([' + C.name + '], '':'', '';'')'
FROM
    sys.columns C
WHERE
    C.object_id = OBJECT_ID('[schema].[table]')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top