Solved

Using variable in MS Sql Query

Posted on 2009-05-05
1
205 Views
Last Modified: 2012-05-06
I've build a stored proc where I loop and set up a part of the query but it shows up empty.

This will work
//////////////////////////////////
SELECT TOP 20 ItemCode, Descr FROM Items WHERE ItemCode like 'cf%'  AND ( brandid = 1 OR brandid = 2 OR brandid = 3 OR brandid = 4 OR brandid = 0)
//////////////////////////////////

But this won't
///////////////////////////////////
DECLARE @setBrand varchar(200)
SET @setBrand = ' AND ( brandid = 1 OR brandid = 2 OR brandid = 3 OR brandid = 4 OR brandid = 0)'

SELECT TOP 20 ItemCode, Descr FROM Items WHERE ItemCode like 'cf%' + @setBrand
///////////////////////////////////

I know this is probably not of a big deal, but I can't figured it out.

Thanks
0
Comment
Question by:maxleb
1 Comment
 
LVL 75

Accepted Solution

by:
Aneesh Retnakaran earned 500 total points
ID: 24308148
EXEC  (    'SELECT TOP 20 ItemCode, Descr FROM Items WHERE ItemCode like ''cf%''  ' + @setBrand )
0

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Join & Write a Comment

INTRODUCTION: While tying your database objects into builds and your enterprise source control system takes a third-party product (like Visual Studio Database Edition or Red-Gate's SQL Source Control), you can achieve some protection using a sing…
PL/SQL can be a very powerful tool for working directly with database tables. Being able to loop will allow you to perform more complex operations, but can be a little tricky to write correctly. This article will provide examples of basic loops alon…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now