-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path38_dynamic_sql_query.sql
64 lines (40 loc) · 1.39 KB
/
38_dynamic_sql_query.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
--dynamic sql query
--normal sql query
select * from CUSTOMERS
where NAME like 'R%'
--converting the above query into dynamic sql query
--method 1 using exec()
declare @var varchar(50) = 'B';
declare @sql varchar(500) = 'select * from CUSTOMERS
where NAME like ''' + @var + '%'''
print(@sql)
--execute the dynamic query
exec(@sql)
--method 2
--using inbuilt stored procedure 'sp_executesql'
declare @var varchar(20) = 'R%';
declare @sql nvarchar(200) = 'select * from CUSTOMERS
where NAME like @var'
execute sp_executesql @sql, N'@var varchar(20)', @var = @var
--using method 2 to collect the output to an output variable
declare @var1 nvarchar(20) = 'Ru%';
declare @Nme nvarchar(20)
declare @query nvarchar(200) = 'SELECT @Nme = NAME
FROM CUSTOMERS
WHERE NAME like @var1'
execute sp_executesql @query, N'@var1 nvarchar(20), @Nme nvarchar(20) OUTPUT',@var1 = @var1,@Nme = @Nme OUTPUT
SELECT @Nme;
--sql injection disadvantage
--creating table sql_injection to demonstrate
/*
create table sql_injection(
test int
)
select * from sql_injection
*/
declare @var2 nvarchar(50) = '''R%''DROP TABLE sql_injection;'
--print(@var2)
declare @sql_q nvarchar(200) = 'SELECT * FROM CUSTOMERS WHERE NAME like'+ @var2
exec(@sql_q)
select * from sql_injection
--'sql_injection' table will be deleted because of the sql injection happened