0

I am creating a stored procedure. Currently queries are being stored in variables. For example:

@sample = 'SELECT * FROM WS_CoolApp_ASample'
@sample += 'Where DATASOURCE.FName = @finder AND DATASOURCE.Age = 23'

I want to remove that 'DATASOURCE.' from the query if a condition is true. So far I've tried:

IF (true)
    REPLACE(@sample, "DATASOURCE.", "")

Why isn't this working?

4
  • Which database engine is this, is it SQL Server? Please be explicit. Commented Sep 6, 2016 at 0:28
  • 2
    Also, your SQL string needs an additional space character after the table name or it runs into the where clause. Commented Sep 6, 2016 at 0:29
  • @DavidG It did have the tsql tag. Commented Sep 6, 2016 at 4:12
  • Yes, it is SQL Server Commented Sep 6, 2016 at 13:46

4 Answers 4

3

You aren't assigning the output of REPLACE() to anything.

@sample = REPLACE(@sample, 'DATASOURCE.', '')
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, actually you were right. I had an if statement with an else statement below it and I changed it to this in the if statement but forgot to do it in the else statement. It's working now!
0
<!-- language: lang-sql -->
DECLARE @sample as nvarchar(500)

set @sample = 'SELECT * FROM WS_CoolApp_ASample';
set @sample += 'Where DATASOURCE.FName = @finder AND DATASOURCE.Age = 23';

-- assign the replaced string back to @sample
set @sample = REPLACE(@sample, 'DATASOURCE.', '')

PRINT @sample

-- prints -> SELECT * FROM WS_CoolApp_ASampleWhere FName = @finder AND Age = 23

Comments

0
DECLARE @sample nvarchar(max)
SET @sample = 'SELECT * FROM WS_CoolApp_ASample'
SET @sample += 'Where DATASOURCE.FName = @finder AND DATASOURCE.Age = 23'

SELECT REPLACE(@sample,'DATASOURCE.','')

I hope this works.

1 Comment

You missed the space between the table and WHERE Also what about the conditional check?
0
DECLARE @sample nvarchar(max)
SET @sample = 'SELECT * FROM WS_CoolApp_ASample '
SET @sample += 'Where DATASOURCE.FName = @finder AND DATASOURCE.Age = 23'
if(@bit_var = 1)
  SET @sample = REPLACE(@sample,'DATASOURCE.','')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.