Monday, January 26, 2009

Dynamic SQL using like

Dynamic SQL was the best choice by far in terms of performance for dynamic search problems,
check article below:
http://www.sommarskog.se/dyn-search-2008.html

It takes a long time from me to write a correct sysntax with LIKE criteria

First I wrote Syntax:

DECLARE @SQL nvarchar(4000)
SET @SQL='SELECT [CategoryName]
FROM [StarterSite_productcatalog].[dbo].[Adventure Works Catalog_CatalogProducts]
where categoryname like ''%@param1%'''
DECLARE @param1 nvarchar(20)
DECLARE @paramlist nvarchar(20)
SET @param1='sl'
SET @paramlist = '@param1 varchar(20)'
EXEC sp_executesql @sql, @paramlist,@param1


I found correct syntax:

DECLARE @SQL nvarchar(4000)
SET @SQL='SELECT [CategoryName]
FROM [StarterSite_productcatalog].[dbo].[Adventure Works Catalog_CatalogProducts]
where categoryname like ''%''+@param1+''%'''
DECLARE @param1 nvarchar(20)
DECLARE @paramlist nvarchar(20)
SET @param1='sl'
SET @paramlist = '@param1 varchar(20)'
EXEC sp_executesql @sql, @paramlist,@param1

1 comment:

Stephen Adam said...

This example leaves you open to Sql Injection.