Passing parameters in SQL stored procedures implements any field ordering

Source: Internet
Author: User

When you're working on a project, you want to do a random sort of table, which is exactly what you can say:

Declare a @parameter in the stored procedure, then the sort after using the query condition, according to my @parameter to implement, and I this @parameter actually pass in is a field value.

Google on the internet, found that there are such examples, most of the TI tree is a multiple-field of any paging stored procedures together, looking very complicated, and I do not need to make paging, no way to achieve it???

I first made one of these:

select * from SiteDetailInfo where SiteBasicId = SiteId And SiteIsCheck = 1 order by  @Parameter desc

To run an error in Query Analyzer:

The%1! identified by the ORDER BY clause A SELECT item contains a variable that is in an expression at the location of the identity column. Variables are allowed in an expression only if they are referenced by a column name.

As if there is a grammatical problem, it is expected, vaguely remember should add a single quote, and so on, asked the netizen Stephen, soon lost the answer came, sure enough is a little grammatical problems.

The amendments are as follows:

create   procedure   proc_test
@fieldname   varchar(50)
as

declare   @sql   varchar(1000)
set   @sql= "update   [table]   set   "   +   @fieldname   +   "= "   +   @fieldname   +   "+1 "
exec(@sql)

go

Or:

declare   @field   varcahr(10)
update   table   (case   @field   when   "字段1名 "   then   set   字段1   =   字段1   +   1
                                                    when   "字段2名 "   then   set   字段2   =   字段2   +   1
                                                    ....   end)

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.