Don't do it like that!
Your code is vulnerable to
SQL Injection[
^].
NEVER use string concatenation to build a SQL query.
ALWAYS use a parameterized query.
In SQL, that means using
sp_executesql[
^] properly:
DECLARE @sqlquery nvarchar(2000);
SET @sqlquery = N'SELECT v.*, vsc.vidhanSabhaConstituencyName
FROM SomeTable As v
INNER JOIN SomeOtherTable As vsv ON <join conditions>
WHERE 1 = 1';
SET @sqlquery = @sqlquery + N' AND v.createdBy = @createdBy';
If @VoterIdNumber Is Not Null SET @sqlquery = @sqlquery + N' AND v.voterIDNumber = @VoterIDNumber';
If @createdDate Is Null SET @createdDate = GetDate();
SET @sqlquery = @sqlquery + N' AND v.dataIsCreated = @createdDate';
EXEC sp_executesql
@sqlquery,
N'@createdBy varchar(50), @VoterIDNumber varchar(50), @createdDate date',
@createdBy = @createdBy,
@VoterIDNumber = @VoterIDNumber,
@createdDate = @createdDate
;
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]