1

As I don't know If the question was quite understandable, perhaps the problem is quite easy.

I'll give it as an example to show what I want:

I have a .sql file like:

CREATE TABLE Instituição(
//stuff inside
GO

CREATE TABLE Tutor(
//stuff inside
GO

CREATE TABLE Funcao(
//stuff inside
GO

with pretty much a bunch of these code alike, the first thing I want is to look up for "CREATE TABLE (something)", and after that this (something) to be replace in another sentence, which goes to:

IF OBJECT_ID(N'SQL_DB..(something)', N'U') IS NOT NULL 
DROP TABLE (something);
GO

to be added before the CREATE TABLE, so the code would be pretty much resulted to:

IF OBJECT_ID(N'SQL_DB..Instituição', N'U') IS NOT NULL 
DROP TABLE Instituição;
GO
CREATE TABLE Instituição(
//stuff inside
GO

IF OBJECT_ID(N'SQL_DB..Tutor', N'U') IS NOT NULL 
DROP TABLE Tutor;
GO
CREATE TABLE Tutor(
//stuff inside
GO

IF OBJECT_ID(N'SQL_DB..Funcao', N'U') IS NOT NULL 
DROP TABLE Funcao;
GO
CREATE TABLE Funcao(
//stuff inside
GO

As I was looking up, the regex code would be like this: find:

CREATE TABLE {:q}

replace:

IF OBJECT_ID(N'SQL_DB..\1', N'U') IS NOT NULL\nDROP TABLE \1;\nGO\nCREATE TABLE \1

But it isn't working, how may I do it properly? Thanks in advance.

2
  • What software are you doing this search and replace in? Commented Jul 4, 2013 at 2:53
  • Microsft SQL Server 2012, but I can use notepad++ if it needs Commented Jul 4, 2013 at 2:55

1 Answer 1

1

In notepad++ you can use this:

Find what:

CREATE TABLE (.*?)\(

Replace with:

IF OBJECT_ID\(N'SQL_DB..\1', N'U'\) IS NOT NULL\nDROP TABLE \1;\nGO\nCREATE TABLE \1\(

Move the cursor to the beginning of the file and hit Replace All.

This will turn your sample input into your sample output.

What did I do? I escaped the parenthesis in the Replace With expression. Also included the ( in the find what (so it is more accurate) and at the end of the Replace With.

Sign up to request clarification or add additional context in comments.

4 Comments

Nice! I only knew about the \1 as the first captured sentence, but may I ask you a little bit of explanation? Well: () these are for capture group, .* is used to reference everything in that part, and the 'slash (' is to reference a single '(' character, which indicates the end of the search, but why the question mark?
The question mark makes the * operator "non-greedy", meaning it will match as little as possible (usually it matches as much as possible). Check this example: regexr.com?35f1u - add a ? after the * and compare. Let me know if it is clear!
Excelent explanation, thank you very much \\Eu ri do brasil 3x0 espanha kkk, obrigado ai :)
Glad I could help! \\hahahuauhuha :D

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.