我在工作中编写了很多 t-sql,并且经常希望有某种类型的扩展可用(例如,TypeScript 之类的东西适用于 Javascript——你可以创建类和所有这些面向对象的东西,它只是编译成标准的 Javascript )。
我想要的一个简单的例子(语义应该在课程之外进行改进):
-- Input:
def $t sysname
$t = 'Table1'
select * from $t
-- Output:
select * from Table1
-- Input (issues: remove last comma, newline characters):
def $t sysname
set $t = 'Table1'
;with Units as (select distinct Unit from $t),
[repeat @i; i=1; i<4]S$i as (select Unit, count(*) C from $t where T = $i group by Unit),[endrepeat]
select distinct [repeat (@i; i=1; i<4)]isnull(S$i.C, 0) C$i,[endrepeat]
from Units u
[repeat @i; i=1; i<4]left join S$i on (u.Unit = S$i.Unit)[endrepeat]
group by [repeat @i; i=1; i<4]S$i.C,[endrepeat]
order by [repeat $i; i=4; i>0]S$i.C desc,[endrepeat]
-- Output:
;with Units as (select distinct Unit from Table1),
S1 as (select Unit, count(*) C from Table1 where T = 1 group by Unit),
S2 as (select Unit, count(*) C from Table1 where T = 2 group by Unit),
S3 as (select Unit, count(*) C from Table1 where T = 3 group by Unit)
select distinct isnull(S1.C, 0) C1, isnull(S2.C, 0) C2, isnull(S3.C, 0) C3
from Units u
left join S1 on (u.Unit = S1.Unit)
left join S2 on (u.Unit = S2.Unit)
left join S3 on (u.Unit = S3.Unit)
group by S1.C, S2.C, S3.C
order by S3.C desc, S2.C desc, S1.C desc
-- Input (sq = singlequotes):
declare @sql varchar(max), @year int
set @year = 2012
set @sql = [sq]
select JobId, InventoryItem
from openquery(MyLinkedServer, '
select JobId, InventoryItem
from Jobs
where year(Created) = {@year}
and Type <> {TypeA}
') x
[endsq]
exec @sql
-- Output:
declare @sql varchar(max)
declare @year int
set @year = 2012
set @sql = '
select JobID, InventoryItem
from openquery (MyLinkedServer, ''
select JobID, InventoryItem
from XXX.Jobs
where year(Created) = ' + convert(varchar, @year) + '
and Type <> ''''TypeA''''
order by "Created" desc
'') x
'
exec @sql
看起来我需要编写自己的 DSL 来实现它,但以前从未使用过它,所以任何想法都更受欢迎。Visual Studio 可视化和建模 SDK (VMSDK) 是否是此类项目的正确选择?它会变得多复杂?:)
编辑 - 建议使用 ORM,但这将直接从 SSMS 运行,而不是从 c# 或 java 之类的语言运行......我的意思是,不会有对象和东西,只有查询。我删除了 c# 标签,因为它具有误导性。这个想法更倾向于 SSMS 插件。