如标题所示。我正在编写一个很长的SQL脚本来对导入的数据集执行一些QC。许多用户将使用该脚本,我希望他们在脚本之上声明一些变量,这些变量将在整个脚本的其余部分使用,而不需要他们进行批量替换或其他:
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 :(得分: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];