A stored procedure is built in SQL Server, and if the required parameter is a mutable set how to handle it?

Source: Internet
Author: User

in SQL Server built-in stored procedures, If a parameter is required to handle a mutable collection

The original stored procedure, @objectIds as a variable parameter, such as 110,98,99

ALTER PROC [dbo]. [Proc_totalscore]

@categoryKey int,

@objectIds VARCHAR (MAX)

As

BEGIN

SELECT C.name,avg (E.score) score from dbo. Sys_com_comment_main m

INNER JOIN dbo.sys_com_coment_extend E on e.commentid=m.id

INNER JOIN dbo.sys_com_category C on E.namekey=c.namekey

WHERE [email protected] and m.datastatus<>99 and M.ischeck=0 and M.objectid in (@objectIds)

GROUP by C.name

END

Call 1 :EXEC [Proc_totalscore] 99902, ' a '

Call 2 :EXEC [Proc_totalscore] 99902, ' 110,97,87 '

A stored procedure is built in SQL Server, and if the required parameter is a mutable set how to handle it?

Search the Internet for a while most are soy sauce paste, there are netizens said in the way of XML, the specific code did not see

compromise, with SQL stitching to achieve the effect of variable parameters  

Let's start with an example of SQL stitching

DECLARE @sql NVARCHAR (MAX)

SET @sql = ' Select 1 MMD '

EXECUTE (@sql)

A compromise stored procedure

ALTER PROC [dbo]. [Proc_totalscore]

@categoryKey VARCHAR (100),

@objectIds VARCHAR (MAX)

As

BEGIN

DECLARE @sql NVARCHAR (MAX)

SET @sql = ' SELECT c.name,avg (e.score) score from dbo. Sys_com_comment_main m

INNER JOIN dbo.sys_com_coment_extend E on e.commentid=m.id

INNER JOIN dbo.sys_com_category C on E.namekey=c.namekey

WHERE m.categorykey= ' [email protected]+ ' and m.datastatus<>99 and M.ischeck=0 and M.objectid in (' [email protected] + ')

GROUP by C.name '

EXECUTE (@sql)

END

Final effect

A stored procedure is built in SQL Server, and if the required parameter is a mutable set how to handle it?

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.