I have a table called Student
sno Name Course Fee Section
1 AAA BCA 10000 A
2 BBB BCom 9000 B
3 CCC BTech 12000 B
I created a temp table called Course_tvp_tbl
CREATE TYPE dbo.Course_tvp_tbl AS TABLE (course VARCHAR(25) NOT NULL PRIMARY KEY (course))
and inserted values into this temp table.
course
BTech
Now I want to delete values from student where the course in temp table course column. We can use the in clause directly but, the table volume is big and also my in clause will contain 1000's of course ids. Tried with creating index(non-clustered as we have clustered already) also having issue as its taking more time OR lock request time out is happening as the query run from multiple instances. I want to use the stored procedure with table value parameters.
CREATE PROCEDURE DBO.DELETE_STUDENTS
@section char(1),
@course_tbl dbo.Course_tvp_tbl READONLY
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM Student where section = @section and course IN (SELECT course FROM @course_tbl)
END
Is the stored procedure delete query having issue. how can I use the temp table course column in delete query In clause?
Followed the TVP Example and wants to use tvp column in deleting the rows from main table
What you've written should work fine; thousands of records is not really much when it comes to data manipulation in modern relational databases (e.g. SQL Server).
You could also accomplish your goal by doing an inner join between
Studentand@course_tblwhich might gain you a slight performance boost if it can make use of the clustered index on the table variable (I haven't tested query plans for these; it's possible theINclause would give you the same query plan as the join approach, but generally, if you can get away with it, joins will perform better thanINclauses).That would look like:
Also, as pointed out in some of the comments, you probably want to give your
@sectionvariable a length (e.g.char(10)instead ofcharorvarchar(30)instead ofvarchar). Not specifying the length can cause it to be treated as achar(1)which is probably not what you're after.