Click here to Skip to main content
15,904,023 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm creating an application in VS 2015, created the database using SQL Server 2016 Express.

To shorten the code in C#, I created Views in SQL Server 2016 so I can just simply call these in my C# code, but some queries will have to produce results that depend on the user input, like what name did they type, number, etc.

Like for example:

C#
string name = txtName.Text.ToString();

command.CommandText = "SELECT * FROM table1 WHERE name = '"+name+"'";


How do I do this in the View? So I won't have to type the whole query in my C# code?
So I can name the query like, 'LoadNames' for example, and then just do this:

C#
command.CommandText = "SELECT * FROM LoadNamesView"


What I have tried:

I've seen:

SQL
DECLARE @theDate DATETIME
SET @theDate = '2010-01-01'


But I'm not sure if this is the correct answer?
Posted
Updated 29-Aug-16 1:58am
v2
Comments
Philippe Mori 28-Aug-16 17:51pm    
You code is subject to SQL injection. Never write code like that.

Looks like you are looking for SQL parameters:
SQL Injection[^]
An advantage of parameters is that it avoid the problem of SQL injection.
In this command
C#
command.CommandText = "SELECT * FROM table1 WHERE name = '"+name+"'";

if the C variable name is input be user, it opens the door to injection.
 
Share this answer
 
I'd suggest to use stored procedures:
How to: Execute a Stored Procedure that Returns Rows[^]
How to: Execute a Query Using a Stored Procedure with In and Out Parameters[^]
How to: Use Stored Procedures that Take Parameters[^]

Advantages:
1. The name of stored procedure is used only
2. A stored procedure provides a way to pass parameters
 
Share this answer
 
v2
If you are with "Views" then no worries.
Below is the way how to handle multiple parameters with SQL Views.

Create a variable called "Where" inside pass all your SQL parameters by concatenating.

Example : If you are having EmployeeMst table and you have created a view called "View_Select_All_Employees" then call this view as below.

C#
string Where = " Where 1=1 ";

if(txtFName.Text.Trim() != Null)
{
   Where += " And EmpFName ='"+ txtFName.Text.Trim() +"'";
}
if(txtLName.Text.Trim() != Null)
{
   Where += " And EmpLName ='"+ txtLName.Text.Trim() +"'";
}


string commandText = "select * from View_Select_All_Employees " + Where;
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("@studentid", 101);



Hope this will help you..!!! :)
 
Share this answer
 
C#
string commandText = "select * from Students where studentid=@studentid"
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("@studentid", 101);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900