Translate

Wednesday, 13 May 2015

Alternative way for execute query like storeprocedure

 create table   Students
 (
 StudentId int primary key not null
 ,StudentName varchar(200) not null    
  )
insert into Students(StudentId,StudentName)values(1,'d')
               insert into Students(StudentId,StudentName)values(4,'Pabitra')
select * from Students

One parameter 

DECLARE @ExecStr NVARCHAR(4000);
SELECT @ExecStr = 'SELECT * FROM dbo.Students WHERE StudentName LIKE @StudentName';
EXEC sp_executesql @ExecStr, N'@StudentName varchar(15)', 'd';



More than one parameter 
DECLARE @ExecStr NVARCHAR(4000);
SELECT @ExecStr = 'SELECT * FROM dbo.Students WHERE StudentName LIKE @StudentName and StudentId LIKE @StudentId';
EXEC sp_executesql @ExecStr, N'@StudentName varchar(15),@StudentId int', 'd', 1;

No comments:

Post a Comment