Problems with stitching strings in SQL Server database stored procedures

Source: Internet
Author: User

  When writing complex stored procedures in a SQL Server database, it is common practice to stitch strings and finally use the Exec sp_executesql ' stitched string ' to query the results.

Look at the code first:

1 -- =============================================2 --author:xxx3 --Create date:2014-09-194 --Description: Get student list information5 -- =============================================6 ALTER PROCEDURE [dbo].[sp_getstudentlist]7     @StudentId INT   --primary Key ID8  as9 BEGINTen      One     SETNOCOUNT on; A      -     DECLARE @SqlSelectResult NVARCHAR(MAX)= "';  -     SET @SqlSelectResult = 'SELECT * from Student as S'; the      -     IF(ISNULL(@StudentId,0)> 0) -     BEGIN -         SET @SqlSelectResult = @SqlSelectResult + 'WHERE s.classid >' + @StudentId; +     END -      +     PRINT(@SqlSelectResult); A      at     EXECsp_executesql@SqlSelectResult; -      -     SETNOCOUNTOFF; - END

Then call the stored procedure: EXEC sp_getstudentlist 1. The results are as follows:

Failed to run.

careful analysis of cause discovery: The stored procedure parameter @StudentId type int (shape), and the custom variable @sqlselectresult is the nvarchar (MAX) string type.

In 23 rows, EXEC sp_executesql @SqlSelectResult; When the concatenation string is executed, an error occurs, and the compiler attempts to convert the string type to int type failed.

This means:when stitching strings in SQL Server, all variables must be string type to correctly splice or error.

Workaround 1: Convert a variable of a non-string type to a string type.

Modify the 18 lines of code to:

        convert (nvarchar), @StudentId);

Workaround 2: Define the parameter as a string type when the stored procedure starts to define
               ALTER PROCEDURE [dbo]. [Sp_getstudentlist]              @StudentId INT   --primary key ID               As
......

Problems with stitching strings in SQL Server database stored procedures

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.