Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'd like to use vim for writing SQL queries, but I haven't figured out yet how to get two key features that I use all the time in programs like SQL Yog.

I usually just start up an instance of Yog in the background, cut-and-paste my SQL into it, hit F12 which auto-formats the whole thing. All the SQL keywords are automatically capitalized as soon as the text is pasted. I then copy it back into whatever other tool I'm using (often SQL Query Browser at work) and go from there.

The benefits of these two features are worth the extra effort. Anyone know how I can set up vim to do this? I still may need to cut and paste back into Query Browser, which is acceptable to me, but I'd like to stick with vim for all my editing.

Thanks.

share|improve this question
    
The SQLUtilities vim script can format SQL quite nicely for you. –  ngm Jul 11 '11 at 10:30

2 Answers 2

up vote 1 down vote accepted

You could put some autocmds for SQL files in your .vimrc that execute a bunch of :ab commands to auto-replace common keywords with their capitalized variants.

Going further, you could also write your own indentation script and attach it to indentexpr.

If you need to do this inline in another file type (i.e., you're writing SQL queries in strings in, say, PHP), you'll probably have to do this in a scratch buffer anyway, or modify your language's ftplugin to use your indentexpr in an "SQL mode."

share|improve this answer
    
To be honest, I don't see the need for capitalization. A judiciously formatted multi-line string with syntax highlighting has always been sufficient for me. –  greyfade Apr 19 '11 at 15:55

I just put this map in my .vimrc:

" prettify sql:
vnoremap <Leader>rp :s/\<update\>\\|\<select\>\\|\<from\>\\|\<where>\\|\<left join\>\\|\<inner join\>\\|\<group by\>\\|\<order by\>/\r\U&/ge<cr><esc>

I've mapped it rp - but choose what you want. (rp = run prettify)

The way to use it is visually select your query (eg*emphasized text* with

vip 

or whatever, then press J to join your query into one line, then run this map.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.