2015-03-13 40 views
0

正如标题中所示。我正在编写一个长的SQL脚本来对导入的数据集执行一些QC操作。许多用户将使用该脚本,并且我希望他们在脚本的顶部声明一些变量,以便在脚本的其余部分使用这些变量,而不需要他们进行大规模替换或其他操作:有什么办法让用户在SQL脚本之上声明变量吗?

declare @lines_in_imported_file int = 13115; 
declare @name_of_user varchar(255) = 'Pr0no'; 

-- DO NOT CHANGE ANYTHING BELOW THIS LINE 

[...] 

select * from imported_data where [username] = @name_of_user; 

[...] 

if (@lines_in_imported_file <> 0) 
    select * from imported_data 
; 

这只有在变量在同一语句中声明和使用时才有效。但是,有什么办法可以完成这个任务(动态SQL除外)?

[--edit--]

create table [CA131RB01_VARS] (
    name varchar(10) 
    , value varchar(10) 
); 

insert into [CA131RB01_VARS] (name, value) values ('lines_in_imported_file', '13115'); 
insert into [CA131RB01_VARS] (name, value) values ('name_of_user', 'pr0no'); 
+0

你可以把变量插入表中。您可以随时随地引用该表,并在脚本末尾销毁该表。 – HoneyBadger 2015-03-13 12:05:29

+0

我一直在想,但它需要用户更新一些插入语句 - 可能会破坏查询。我会想到声明一些变量不太容易出错:) – Pr0no 2015-03-13 12:11:08

+0

你是什么意思“它需要用户更新一些插入语句”?你可以自己创建表格并插入用户填充的变量,对吧?也许我不明白你的目标足够了...... – HoneyBadger 2015-03-13 12:13:45

回答

1

我的意思是沿着这些路线的东西:

declare @lines_in_imported_file int = 13115; 
declare @name_of_user varchar(255) = 'Pr0no'; 

-- DO NOT CHANGE ANYTHING BELOW THIS LINE 

create table [CA131RB01_VARS] (
    name varchar(10) 
    , value varchar(10) 
); 

insert into [CA131RB01_VARS] (name, value) values ('lines_in_imported_file', @lines_in_imported_file); 
insert into [CA131RB01_VARS] (name, value) values ('name_of_user', @name_of_user); 

[...] 

select  * 
from   imported_data id 
inner join [CA131RB01_VARS] vars 
     on  vars.value = id.[username] 
where  vars.name = 'name_of_user' 

[...] 

if ((select value from CA131RB01_VARS where name = 'lines_in_imported_file') <> 0) 
    select * from imported_data 
; 

drop table [CA131RB01_VARS]; 
相关问题