0

I want a select statement like this

select concat ('insert into Place (Id, Name) values (' Id, ',', '''', PlaceName , '''', ')' ) from Address 

The values are:

Id PlaceName ------------------ 1 Amsterdam 2 's-Gravenhage 3 Rotterdam 4 Utrecht 5 's-Hertogenbosch 6 Groningen 

How can you create an output like this?

insert into Place (Id, Name) values (1, 'Amsterdam') insert into Place (Id, Name) values (2, '''s-Gravenhage') insert into Place (Id, Name) values (3, 'Rotterdam') insert into Place (Id, Name) values (4, 'Utrecht') insert into Place (Id, Name) values (5, '''s-Hertogenbosch') insert into Place (Id, Name) values (6, 'Groningen') 

I tried to use Replace(PlaceName, ''', '''') or something...

5
  • 2
    Why do this at all? The problem is caused by the use of dynamic sql, not the quotes Commented Oct 27, 2020 at 16:13
  • For showing what I want to do. Commented Oct 27, 2020 at 16:14
  • Again, why do this at all? Why use dynamic sql? You won't have any issues if you use parameterized queries. Or if you export the data with eg bcp or any other tool, then import them to another database Commented Oct 27, 2020 at 16:14
  • I want a simple solution for creating insert-statements. It's just for once. and I want to replace a single ' into a double '. Commented Oct 27, 2020 at 16:17
  • But that doesn't answer the why @PanagiotisKanavos is asking here, user1531040. I smell an XY Problem here. Commented Oct 27, 2020 at 16:23

2 Answers 2

2

You were very close in your initial attempt, you just need to escape the single quotes by doubling them up, as is actually being done in your first sql statement:

replace(PlaceName, '''', '''''') 
Sign up to request clarification or add additional context in comments.

Comments

1

Using replace:

select FORMATMESSAGE('INSERT INTO Place(id, Name) VALUES (%i, ''%s'');' ,Id ,REPLACE(PlaceName, '''', '''''')) from Address; 

db<>fiddle demo

Warning: There are other, better ways of scripting data. Generating INSERT INTO is supported by SSMS or Azure Data Studio.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.