自动化SQL报价和NewLine

时间:2015-11-17 13:36:31

标签: c# .net tsql

我经常会从SSMS获得TSQL,我需要在c#.NET中使用 添加"和环境.NewLine是乏味的 是否有工具/宏来自动化这种格式?

TSQL raw

select * 
  from hmAdjusted 
 order by [hmAdjusted] desc;

C#.NET中的TSQL

string select = "select * " + Environment.NewLine + 
                "  from hmAdjusted " + Environment.NewLine + 
                " order by [hmAdjusted] desc;";

我不是要求其他方法 我特别询问如何自动化这种特定的格式 对或错是我为这个项目格式化代码的方式。

5 个答案:

答案 0 :(得分:4)

由于这是您想要听到的全部内容:不,Visual Studio中没有开箱即用的工具可以自动执行此操作。随意编写自己的(附录:您可能会成功摆弄Visual Studio的查找和替换功能)。

答案 1 :(得分:1)

您可以使用@"多行文字" multiline string in c# ......

编辑 for"我专门讨论如何自动化格式化。"

尝试使用" ctrl + shift + h"替换文件。在编辑器中选择复制的SQL,并使用find-options替换一些。

  1. 启用正则表达式。
  2. 用"替换^(行首) (选择中的字符串开头)。
  3. 用"替换\ r?\ n + Environment.NewLine + \ r \ n
  4. 你需要用&#34 ;;关闭最后一行。虽然manualy。

答案 2 :(得分:1)

看起来有点傻,但我认为这就是你所需要的:

    public static void Main()
    {
        var query = "select * from hmAdjusted order by [hmAdjusted] desc;";
        var result = MyQueryFormatter(query);
        Console.WriteLine(result);
    }

    public static string MyQueryFormatter(string query)
    {
        var beforeWhatAddNewLine = new string[] { "from", "order" };
        var temp = query.Split(' ');
        var tempLength = temp.Count();
        var result = new StringBuilder();
        for (int i = 0; i < tempLength; i++)
        {
            if (beforeWhatAddNewLine.Contains(temp[i]))
            {
                result.Append(Environment.NewLine);
            }
            else if (i != 0)
            {
                result.Append(" ");
            }
            result.Append(temp[i]);
        }
        return result.ToString();
    }

结果:

Peter Pan - MSFT

您只需将beforeWhatAddNewLine集合配置一次,然后使用它。此外,如果您需要其他解决方案,请通过LINQ完成此操作。

答案 3 :(得分:0)

string.Join如何让您保持格式

            var select = string.Join("\n", "select * ",
                                           "  from hmAdjusted ",
                                           " order by [hmAdjusted] desc;");

答案 4 :(得分:0)

根据EakTheCat的评论,正则表达式可能是更好的方式 但我已经写了一个小的独立实用工具 所有标签看起来都很奇怪,但是当我粘贴时,我需要使用的标签数量为

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        DataContext="{Binding RelativeSource={RelativeSource self}}" 
        Title="SQL Formatter" Height="600" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <ScrollViewer Grid.Row="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <TextBox  AcceptsReturn="True" AcceptsTab="True"  
                      Text="{Binding Path=Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
        </ScrollViewer>
        <ScrollViewer Grid.Row="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <TextBox  Text="{Binding Path=Output, Mode=OneWay}"/>
        </ScrollViewer>
    </Grid>
</Window>

using System.ComponentModel;
namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        public MainWindow()
        {
            InitializeComponent();
        }
        private string input = "input raw TSQL here";
        public string Input
        {
            set
            {
                if (input == value) return;
                input = value;
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("string query = ");
                bool first = true;
                foreach(string line in input.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
                {
                    if (string.IsNullOrEmpty(line))
                        continue;
                    if (first)
                        first = false;
                    else
                        sb.AppendLine(" + Environment.NewLine + ");
                    sb.Append("\t\t\t\t\t\t\"" + line + " \"");
                }
                sb.Append(";");
                Output = sb.ToString();
            }
            get { return input; }
        }
        private string output = string.Empty;
        public string Output
        {
            set
            {
                if (output == value) return;
                output = value;
                NotifyPropertyChanged("Output");
            }
            get { return output; }
        }
    }
}