March 5, 2005 at 3:29 am
March 5, 2005 at 5:37 am
Something like this should cut it for you:
Declare @SQL as varchar(200)
Declare @Value int
Set @SQL = 'SELECT ID, Name, Description FROM Table1 WHERE Name = ''A'''
IF @Value = 0
BEGIN
Set @SQL = @SQL + ' AND ID = 100'
END
ELSE
BEGIN
Set @SQL = @SQL + ' AND ID = 200'
END
execute(@SQL)
March 5, 2005 at 9:44 am
Actually, it can be done without the overhead of Dynamic SQL by using a CASE statement in the WHERE clause....
FROM Table1
WHERE Name = 'AA'
AND ID = CASE
WHEN @Value = 0 THEN 100
ELSE 200
END
--Jeff Moden
Change is inevitable... Change for the better is not.
March 6, 2005 at 8:50 pm
Dear Grasshopper,
Thanks for your answer but my query statement is long, over 255 characters. So I have to seperate many strings, isn't it?
Best Regards,
MK.
March 7, 2005 at 4:04 am
Morean,
SellerTools' answer can easily be modified to handle 8000 characters just by changing "Declare @SQL as varchar(200)" to "Declare @SQL as varchar(8000)". Still, it's dynamic SQL and might be better off adding the CASE statement to the WHERE clause... and then you don't have to worry about such things, either.
--Jeff Moden
Change is inevitable... Change for the better is not.
March 7, 2005 at 4:16 am
hey grasshopper,
I agree with Jeff that more than likely, you are better off making a smarter statement rather than resorting to dynamic SQL. I think the only time I personally have had to use dynamic SQL was in the creation of tables. I tdoes have its places, but with the example that you gave, either a CASE statement would work, or even better would be something like;
Create Procedure dbo.MyProcedure
(
@Value as int
)
Declare @IDValue as int
if @Value=0
BEGIN
Set @IDValue = 100
End
Else
BEGIN
SET @IDValue = 200
END
BEGIN
SELECT
ID,
Name,
Description
FROM Table1 WHERE Name = 'AA' AND ID = @IDValue
END
GO
March 8, 2005 at 1:29 am
Grasshopper,
Thanks a lot!
MK.
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply