SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Dynamic Sql
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

ryoka012
Starting Member

Philippines
20 Posts

Posted - 07/24/2013 :  04:51:16  Show Profile  Reply with Quote
Hi,

im using dynamic sql i have an error i just would like to get your opinion in where is have an error "Incorrect syntax near the keyword 'like'."

declare @FieldName as varchar(50)
,@SearchItem as varchar(50)
,@PCInventory as varchar(50)
,@sqlTableName as varchar(100)
,@sqlFieldName as varchar(100)
,@sqlSearchItem as varchar(100)
set @FieldName='Department'
set @SearchItem='PCC'


set @sqlTableName='SELECT * FROM PCInventory ' + @FieldName
set @sqlFieldName=@sqlTableName + 'where' + @FieldName
set @sqlSearchItem=@sqlFieldName like '%' + @SearchItem + '%'
exec(@sqlSearchItem)

thanks.

SwePeso
Patron Saint of Lost Yaks

Sweden
30240 Posts

Posted - 07/24/2013 :  05:02:36  Show Profile  Visit SwePeso's Homepage  Reply with Quote
DECLARE @FieldName VARCHAR(50) = 'Department',
	@SearchItem VARCHAR(50) = 'PCC',
	@PCInventory VARCHAR(50),
	@sqlTableName VARCHAR(100),
	@sqlFieldName VARCHAR(100),
	@sqlSearchItem VARCHAR(100);

-- Prevent SQL Injection
SET	@sqlTableName = 'SELECT * FROM PCInventory ';
SET	@sqlFieldName = @sqlTableName + 'WHERE ' + QUOTENAME(@FieldName);
SET	@sqlSearchItem = @sqlFieldName + ' LIKE ' + QUOTENAME('%' + @SearchItem + '%', '''') + ';';

-- Display the final result
EXEC	(@sqlSearchItem)



Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA
Go to Top of Page

ryoka012
Starting Member

Philippines
20 Posts

Posted - 07/24/2013 :  05:05:15  Show Profile  Reply with Quote
thanks SwePeso..it works like a charm..
Go to Top of Page

madhivanan
Premature Yak Congratulator

India
22755 Posts

Posted - 07/28/2013 :  11:42:23  Show Profile  Send madhivanan a Yahoo! Message  Reply with Quote
Always read this www.sommarskog.se/dynamic_sql.html

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000