Why does this sql function not work with REPLACE? - sql

I am having a problem with my sql function. The following function operates as expect but when I substitute, it only returns one row:
CAST(t.ColumnName as nvarchar(100))
for:
REPLACE(CAST(t.ColumnName as nvarchar(100)), 'ID', 'Id')
What is wrong? Here is my calling code:
PRINT dbo.CreatePocoFromTable('dbo.OnePoundFish')
Here is the function itself:
CREATE FUNCTION [dbo].[CreatePocoFromTable]
(#SchemaAndName nvarchar(200))
RETURNS Nvarchar(MAX) AS
BEGIN
/* Example call:
PRINT dbo.CreatePocoFromTable('dbo.OnePoundFish')
*/
DECLARE #TableName NVARCHAR(100) = SUBSTRING(#SchemaAndName , CHARINDEX('.', #SchemaAndName ) + 1, LEN(#SchemaAndName ))
DECLARE #TableSchema NVARCHAR(100) = SUBSTRING(#SchemaAndName , 1, CHARINDEX('.', #SchemaAndName ) - 1)
DECLARE #result Nvarchar(max) = ''
SET #result = #result + 'using System;' + CHAR(13) + CHAR(13)
IF (#TableSchema IS NOT NULL)
BEGIN
SET #result = #result + 'namespace ' + #TableSchema + CHAR(13) + '{' + CHAR(13)
END
SET #result = #result + 'public class ' + #TableName + CHAR(13) + '{' + CHAR(13)
SET #result = #result + '#region Instance Properties' + CHAR(13)
SELECT #result = #result + CHAR(13)
-- BL/DAL/DataRepository Entity attributes
+ '[DataField("' + t.ColumnName + '")]' + CHAR(13)
+ ' public ' + t.ColumnType + ' ' + CAST(t.ColumnName as nvarchar(100)) + ' { get; set; } ' + CHAR(13)
FROM
(
SELECT
c.COLUMN_NAME AS ColumnName
, CASE c.DATA_TYPE
WHEN 'bigint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int64?' ELSE 'Int64' END
WHEN 'binary' THEN 'Byte[]'
WHEN 'bit' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Boolean?' ELSE 'Boolean' END
WHEN 'char' THEN 'String'
WHEN 'date' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetime' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetime2' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'datetimeoffset' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTimeOffset?' ELSE 'DateTimeOffset' END
WHEN 'decimal' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'float' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Single?' ELSE 'Single' END
WHEN 'image' THEN 'Byte[]'
WHEN 'int' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int32?' ELSE 'Int32' END
WHEN 'money' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'nchar' THEN 'String'
WHEN 'ntext' THEN 'String'
WHEN 'numeric' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'nvarchar' THEN 'String'
WHEN 'real' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Double?' ELSE 'Double' END
WHEN 'smalldatetime' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'smallint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Int16?' ELSE 'Int16'END
WHEN 'smallmoney' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Decimal?' ELSE 'Decimal' END
WHEN 'text' THEN 'String'
WHEN 'time' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'TimeSpan?' ELSE 'TimeSpan' END
WHEN 'timestamp' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'DateTime?' ELSE 'DateTime' END
WHEN 'tinyint' THEN
CASE C.IS_NULLABLE
WHEN 'YES' THEN 'Byte?' ELSE 'Byte' END
WHEN 'uniqueidentifier' THEN 'Guid'
WHEN 'varbinary' THEN 'Byte[]'
WHEN 'varchar' THEN 'String'
ELSE 'Object'
END AS ColumnType
, c.ORDINAL_POSITION
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.TABLE_NAME = #TableName and ISNULL(#TableSchema, c.TABLE_SCHEMA) = c.TABLE_SCHEMA
) t
ORDER BY t.ORDINAL_POSITION
SET #result = #result + CHAR(13) + '#endregion Instance Properties' + CHAR(13)
SET #result = #result + '}' + CHAR(13)
IF (#TableSchema IS NOT NULL)
BEGIN
SET #result = #result + CHAR(13) + '}'
END
RETURN #Result
END
Thanks :)

only the interesting part ...
SELECT #result = #result + CHAR(13)
-- BL/DAL/DataRepository Entity attributes
+ '[DataField("' + CAST(REPLACE(t.ColumnName , 'ID', 'Id') as nvarchar(100)) + '")]' + CHAR(13)
-- + '[DataField("' + t.ColumnName + '")]' + CHAR(13)
+ ' public ' + t.ColumnType + ' ' + CAST(t.ColumnName as nvarchar(100)) + ' { get; set; } ' + CHAR(13)
FROM

Is your sql server set to be case sensitive? If not (and I believe it's not by default) then replace based on different case of the same word will not work.
See this link to change the collation to a case sensitive one How do I change SQL Server 2005 to be case sensitive?

Related

Syntax error in SQL , Incorrect syntax near ''

What is wrong in this?
The error comes from this section;
AND ('''+#searchText+''' = '''' OR (ISNULL(CAST(t1.id as varchar(10)),'''') + '' '' +
ISNULL(CAST(FORMAT(t1.reading_date,#dateformat) as varchar(12)),'''')+'' '' +
ISNULL(t2.description,'''') + '' '' +
ISNULL(t3.equipment_no,'''') + '' '' +
ISNULL(t4.description,'''') + '' '' +
ISNULL(CAST(t1.actual_usage as nvarchar(16)),'''') + '' '' +
ISNULL(t5.uom_code,'''') + '' '' +
ISNULL(CAST(t1.actual_cost as nvarchar(16)),'''') + '' '' +
ISNULL(t6.currency_code,'''') + '' '' +
ISNULL(t1.comment,'''') + '' '' +
ISNULL(CAST(FORMAT(t1.actual_date,#dateformat) as varchar(12)),'''')) LIKE ''%'' '''+#searchText+''' ''%'')
The error:
Msg 102, Level 15, State 1, Line 59
Incorrect syntax near ''.
You can use CONCAT(string1, string2, ...., string_n) instead of doing it manually using + operator. Also, use COALESCE to return column value or empty string. This will simplify the query.
Sample for using CONCAT()
DECLARE #searchText AS VARCHAR(50) = 'SearchMe'
DECLARE #sqlQuery2 AS VARCHAR(5000)
DECLARE #Column1 AS VARCHAR(50) = 'TestValue1'
SET #sqlQuery2 = ' FROM Table
WHERE Column1 = ''' + #Column1 + '''
AND ('''+#searchText+''' = '''' OR (CONCAT(
ISNULL(CAST(t1.id as varchar(10)), '''')
, '' ''
, ISNULL(CAST(FORMAT(t1.reading_date,#dateformat) as varchar(12)), '''')
, '' ''
, ISNULL(t2.description, '''')
, '' ''
, ISNULL(t3.equipment_no, '''')
, '' ''
, ISNULL(t4.description, '''')
, '' ''
, ISNULL(CAST(t1.actual_usage as nvarchar(16)), '''')
, '' ''
, ISNULL(t5.uom_code, '''')
, '' ''
, ISNULL(CAST(t1.actual_cost as nvarchar(16)), '''')
, '' ''
, ISNULL(t6.currency_code, '''')
, '' ''
, ISNULL(t1.comment, '''')
, '' ''
, ISNULL(CAST(FORMAT(t1.actual_date,#dateformat) as varchar(12)), ''''))
)) LIKE ''% ' + #searchText + ' %''
)
ORDER BY someColumn '
select #sqlQuery2
Also noted that LIKE statement string in your code will return syntax error.
Replace the string
LIKE ''%'' ''' + #searchText + ''' ''%''
by this
LIKE ''% ' + #searchText + ' %''
I hope it will help.

Filter data by keywords and note where they were found

so i have a query at the moment.
SELECT *
FROM TABLE1
It yields besides other stuff 4 colums which contain text "Textbox1" "Textbox2" "Textbox3" "Textbox4".
I now want to filter this query by keywords in those text boxes. Basically the user can enters 0 to 5 keywords and the rows from TABLE1 should only show if at least one keyword was found in one of the textboxes. Also a new column should be added that for every keyword that was found in a textbox should say which keyword and in which textboxes it was found.
The query itself will later run in SSRS which is where the user puts in the keywords. So the keywords are accasable as varchars. For the query you can use this:
DECLARE #Keyword1 AS VARCHAR(100) = '';
DECLARE #Keyword2 AS VARCHAR(100) = '';
DECLARE #Keyword3 AS VARCHAR(100) = '';
DECLARE #Keyword4 AS VARCHAR(100) = '';
DECLARE #Keyword5 AS VARCHAR(100) = '';
Thanks for any help.
Edit:
This is a very unelegant solution and it's not exactly what you wanted but hopefully close enough.
To improve it, especially if you are goning to extend this to more column/keywords I would consider unpivoting the data, testing each row and then aggregating the result of that back up again.
DECLARE #t TABLE (T1 varchar(100), T2 varchar(100), T3 varchar(100), T4 varchar(100))
INSERT INTO #t VALUES
(1, 11, 203, 30),
(8898, 54452, 1222, 12122)
DECLARE #k1 varchar(100) = '1'
DECLARE #k2 varchar(100) = '22'
SET #k1 = '%' + #k1 + '%'
SET #k2 = '%' + #k2 + '%'
SELECT
*
, CASE WHEN T1 like #k1 THEN '1:T1 ' ELSE '' END +
CASE WHEN T2 like #k1 THEN '1:T2 ' ELSE '' END +
CASE WHEN T3 like #k1 THEN '1:T3 ' ELSE '' END +
CASE WHEN T4 like #k1 THEN '1:T4 ' ELSE '' END +
CASE WHEN T1 like #k2 THEN '2:T1 ' ELSE '' END +
CASE WHEN T2 like #k2 THEN '2:T2 ' ELSE '' END +
CASE WHEN T3 like #k2 THEN '2:T3 ' ELSE '' END +
CASE WHEN T4 like #k2 THEN '2:T4 ' ELSE '' END
As Found
FROM #t
This give the following results.
With the help of Alan Schofield i found the solution that i need.
SELECT * from( Select*,
CASE WHEN Textbox1 like '%'+#Keyword1+'%' AND #Keyword1 <> '' THEN #Keyword1 +', ' ELSE '' END +
CASE WHEN Textbox1 like '%'+#Keyword2+'%' AND #Keyword2 <> '' THEN #Keyword2 +', ' ELSE '' END +
CASE WHEN Textbox1 like '%'+#Keyword3+'%' AND #Keyword3 <> '' THEN #Keyword3 +', ' ELSE '' END +
CASE WHEN Textbox1 like '%'+#Keyword4+'%' AND #Keyword4 <> '' THEN #Keyword4 +', ' ELSE '' END +
CASE WHEN Textbox1 like '%'+#Keyword5+'%' AND #Keyword5 <> '' THEN #Keyword5 +', ' ELSE '' END
As Textbox1found,
CASE WHEN Textbox2 like '%'+#Keyword1+'%' AND #Keyword1 <> '' THEN #Keyword1 +', ' ELSE '' END +
CASE WHEN Textbox2 like '%'+#Keyword2+'%' AND #Keyword2 <> '' THEN #Keyword2 +', ' ELSE '' END +
CASE WHEN Textbox2 like '%'+#Keyword3+'%' AND #Keyword3 <> '' THEN #Keyword3 +', ' ELSE '' END +
CASE WHEN Textbox2 like '%'+#Keyword4+'%' AND #Keyword4 <> '' THEN #Keyword4 +', ' ELSE '' END +
CASE WHEN Textbox2 like '%'+#Keyword5+'%' AND #Keyword5 <> '' THEN #Keyword5 +', ' ELSE '' END
As Textbox2found,
CASE WHEN Textbox3 like '%'+#Keyword1+'%' AND #Keyword1 <> '' THEN #Keyword1 +', ' ELSE '' END +
CASE WHEN Textbox3 like '%'+#Keyword2+'%' AND #Keyword2 <> '' THEN #Keyword2 +', ' ELSE '' END +
CASE WHEN Textbox3 like '%'+#Keyword3+'%' AND #Keyword3 <> '' THEN #Keyword3 +', ' ELSE '' END +
CASE WHEN Textbox3 like '%'+#Keyword4+'%' AND #Keyword4 <> '' THEN #Keyword4 +', ' ELSE '' END +
CASE WHEN Textbox3 like '%'+#Keyword5+'%' AND #Keyword5 <> '' THEN #Keyword5 +', ' ELSE '' END
As Textbox3found,
CASE WHEN Textbox4 like '%'+#Keyword1+'%' AND #Keyword1 <> '' THEN #Keyword1 +', ' ELSE '' END +
CASE WHEN Textbox4 like '%'+#Keyword2+'%' AND #Keyword2 <> '' THEN #Keyword2 +', ' ELSE '' END +
CASE WHEN Textbox4 like '%'+#Keyword3+'%' AND #Keyword3 <> '' THEN #Keyword3 +', ' ELSE '' END +
CASE WHEN Textbox4 like '%'+#Keyword4+'%' AND #Keyword4 <> '' THEN #Keyword4 +', ' ELSE '' END +
CASE WHEN Textbox4 like '%'+#Keyword5+'%' AND #Keyword5 <> '' THEN #Keyword5 +', ' ELSE '' END
AS Textbox4found
FROM Table1)as Result
WHERE Result.Textbox1found <> '' OR Result.Textbox2found <> '' OR Result.Textbox3found <> '' OR Result.Textbox4found <> '' or (#Keyword1='' AND #Keyword2='' AND #Keyword3='' AND #Keyword4='' AND #Keyword5='')
I switched to a Textbox based query which will generat for every textbox a column with the keywords found in that textbox.

SQL Server: Conversion failed when converting date and/or time from character string

I want to check if the columns of a table contain null value and if so assign the 0 value. I had problem because there where UniqueIdentifier column existing. So I change my code to assign '0' value. But now I have a problem when there is DateTime column.
Here is the code:
Select #sql = #sql + 'Case when IsNull(i.[' + Column_Name +
'],''0'') = IsNull(d.[' + Column_name + '],''0'') then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
where table_name = 'Users' and column_name <>'rowguid' and column_name <>'modifieddate'
Another failed attempt:
Select #sql = #sql +
'Case
when IsDate(i.['+Column_Name+']) =1 and IsDate(d.['+Column_Name+']) =1 and IsNull(i.[' + Column_Name + '],1/1/1900) = IsNull(d.[' + Column_name + '],1/1/1900)
then ''''
when IsNull(i.[' + Column_Name + '],''0'') = IsNull(d.[' + Column_name + '],''0'')
then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
where table_name = 'Users' and column_name <>'rowguid' and column_name <>'modifieddate'
Full code:
if #Action = 'U'
BEGIN
Select #sql = #sql +
'Case when IsNull(i.[' + Column_Name +
'],' + CASE DATA_TYPE
WHEN 'int' THEN '0'
WHEN 'bigint' THEN '0'
WHEN 'tinyint' THEN '0'
WHEN 'uniqueidentifier' THEN '''0'''
WHEN 'varchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'nvarchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'date' THEN CHAR(39) + '1/1/1900' + CHAR(39)
WHEN 'datetime' THEN CHAR(39) + '1/1/1900 00:00:00' + CHAR(39)
ELSE ''
END + ') = IsNull(d.[' + Column_name + '],'+
CASE DATA_TYPE
WHEN 'int' THEN '0'
WHEN 'bigint' THEN '0'
WHEN 'tinyint' THEN '0'
WHEN 'uniqueidentifier' THEN '''0'''
WHEN 'varchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'nvarchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'date' THEN CHAR(39) + '1/1/1900' + CHAR(39)
WHEN 'datetime' THEN CHAR(39) + '1/1/1900 00:00:00' + CHAR(39)
ELSE ''
END + ') then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
where table_name = 'Users' and column_name <>'rowguid' and column_name <>'modifieddate'
--Define output parameter
set #ParmDefinition = '#OutString varchar(max) OUTPUT'
--Format sql
set #sql = 'Select #OutString = '
+ Substring(#sql,1 , len(#sql) -1) +
' From dbo.Users i ' --Will need to be updated for target schema
+ ' inner join #tempTrigT d on
i.id = d.id' --Will need to be updated for target schema
--Execute sql and retrieve desired column list in output parameter
exec sp_executesql #sql, #ParmDefinition, #OutString OUT
Here an example how a corresponding CASE might look like -however, it is NOT complete and you might want to extend / redesign it a little:
Select #sql = #sql + 'Case when IsNull(i.[' + Column_Name +
'],' + CASE DATA_TYPE
WHEN 'int' THEN '0'
WHEN 'bigint' THEN '0'
WHEN 'tinyint' THEN '0'
WHEN 'varchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'nvarchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'date' THEN CHAR(39) + '1900-01-01' + CHAR(39)
ELSE ''
END + ') = IsNull(d.[' + Column_name + '],'+
CASE DATA_TYPE
WHEN 'int' THEN '0'
WHEN 'bigint' THEN '0'
WHEN 'tinyint' THEN '0'
WHEN 'varchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'nvarchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'date' THEN CHAR(39) + '1900-01-01' + CHAR(39)
ELSE ''
END + ') then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns

SQL server script for generating script for table

I have following situation: I'm working on project where data base contains hundreds of tables, and very often I know what table I need to generate script for, but finding it in the list of all tables takes a lot of time. I would like to know, is there a way to write script which will generate script for table. Since I already know table name, it's easier for me just to type it than search it in huge list of similar names.
Yes, you can definitely write your own procedure to generate scripts for a given table name which will be provided as parameter. In my example, I am passing 'dbo.TABLE1' as a parameter to this query:
(You can wrap this into a stored procedure, of course)
DECLARE
#object_name SYSNAME = 'dbo.TABLE1'
, #object_id INT = object_id('dbo.TABLE1')
, #SQL NVARCHAR(MAX)
SELECT
#object_name = '[' + OBJECT_SCHEMA_NAME(o.[object_id]) + '].[' + OBJECT_NAME([object_id]) + ']'
, #object_id = [object_id]
FROM (SELECT [object_id] = #object_id) o
SELECT #SQL = 'CREATE TABLE ' + #object_name + CHAR(13) + '(' + CHAR(13) + STUFF((
SELECT CHAR(13) + ' , [' + c.name + '] ' +
CASE WHEN c.is_computed = 1
THEN 'AS ' + OBJECT_DEFINITION(c.[object_id], c.column_id)
ELSE
CASE WHEN c.system_type_id != c.user_type_id
THEN '[' + SCHEMA_NAME(tp.[schema_id]) + '].[' + tp.name + ']'
ELSE '[' + UPPER(tp.name) + ']'
END +
CASE
WHEN tp.name IN ('varchar', 'char', 'varbinary', 'binary')
THEN '(' + CASE WHEN c.max_length = -1
THEN 'MAX'
ELSE CAST(c.max_length AS VARCHAR(5))
END + ')'
WHEN tp.name IN ('nvarchar', 'nchar')
THEN '(' + CASE WHEN c.max_length = -1
THEN 'MAX'
ELSE CAST(c.max_length / 2 AS VARCHAR(5))
END + ')'
WHEN tp.name IN ('datetime2', 'time2', 'datetimeoffset')
THEN '(' + CAST(c.scale AS VARCHAR(5)) + ')'
WHEN tp.name = 'decimal'
THEN '(' + CAST(c.[precision] AS VARCHAR(5)) + ',' + CAST(c.scale AS VARCHAR(5)) + ')'
ELSE ''
END +
CASE WHEN c.collation_name IS NOT NULL AND c.system_type_id = c.user_type_id
THEN ' COLLATE ' + c.collation_name
ELSE ''
END +
CASE WHEN c.is_nullable = 1
THEN ' NULL'
ELSE ' NOT NULL'
END +
CASE WHEN c.default_object_id != 0
THEN ' CONSTRAINT [' + OBJECT_NAME(c.default_object_id) + ']' +
' DEFAULT ' + OBJECT_DEFINITION(c.default_object_id)
ELSE ''
END +
CASE WHEN cc.[object_id] IS NOT NULL
THEN ' CONSTRAINT [' + cc.name + '] CHECK ' + cc.[definition]
ELSE ''
END +
CASE WHEN c.is_identity = 1
THEN ' IDENTITY(' + CAST(IDENTITYPROPERTY(c.[object_id], 'SeedValue') AS VARCHAR(5)) + ',' +
CAST(IDENTITYPROPERTY(c.[object_id], 'IncrementValue') AS VARCHAR(5)) + ')'
ELSE ''
END
END
FROM sys.columns c WITH(NOLOCK)
JOIN sys.types tp WITH(NOLOCK) ON c.user_type_id = tp.user_type_id
LEFT JOIN sys.check_constraints cc WITH(NOLOCK)
ON c.[object_id] = cc.parent_object_id
AND cc.parent_column_id = c.column_id
WHERE c.[object_id] = #object_id
ORDER BY c.column_id
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 7, ' ') +
ISNULL((SELECT '
, CONSTRAINT [' + i.name + '] PRIMARY KEY ' +
CASE WHEN i.index_id = 1
THEN 'CLUSTERED'
ELSE 'NONCLUSTERED'
END +' (' + (
SELECT STUFF(CAST((
SELECT ', [' + COL_NAME(ic.[object_id], ic.column_id) + ']' +
CASE WHEN ic.is_descending_key = 1
THEN ' DESC'
ELSE ''
END
FROM sys.index_columns ic WITH(NOLOCK)
WHERE i.[object_id] = ic.[object_id]
AND i.index_id = ic.index_id
FOR XML PATH(N''), TYPE) AS NVARCHAR(MAX)), 1, 2, '')) + ')'
FROM sys.indexes i WITH(NOLOCK)
WHERE i.[object_id] = #object_id
AND i.is_primary_key = 1), '') + CHAR(13) + ');'
SELECT #SQL
Here is a link to a stored proc code , you can add and execute by giving just the table name to get the DDL.
http://www.stormrage.com/SQLStuff/sp_GetDDLa_Latest.txt

A constant expression was encountered in the ORDER BY list

Below is my dynamic query and it's not working.
It threw:
A constant expression was encountered in the ORDER BY list, position 2.
Original dynamic query:
SET #QueryVendorName = ';WITH
cteForPriceVen AS (select AI.ItemID, AI.ItemPartNumber as ItemPartNumber, AI.ItemDescription, cteForPrice.VendorPrice as Price, cteForPrice.UpdatedDate as UpdatedDate, cteForPrice.IsLocked as IsLocked
from AerospaceItems (nolock) AI
inner join VendorItemPricing (nolock) cteForPrice
on AI.ItemPartNumber = cteForPrice.ItemPartNumber where cteForPrice.VendorName = ''' + #VendorName + ''' AND
cteForPrice.ObsoleteItem = ''' + cast (#ItemType as char(1)) + ''') select * from cteForPriceVen'
SET #OrderQuery = '
WHERE (''' + cast (#Description as varchar(250)) + ''' = '''' OR cteForPriceVen.ItemDescription like ''%' + cast (#Description as varchar(250)) + '%'')
AND (''' + cast (#PartNumber as varchar(99)) + ''' = '''' OR cteForPriceVen.ItemPartNumber like ''%' + cast (#PartNumber as varchar(99)) + '%'')
AND (''' + cast (#PriceFrom as varchar(25)) + ''' = '''' OR Price >= ''' + cast (#PriceFrom as varchar(99)) + ''')
AND (''' + cast (#PriceTo as varchar(25)) + ''' = '''' OR Price <= ''' + cast (#PriceTo as varchar(99)) + ''')
AND (''' + cast (#DateFrom as varchar(25)) + ''' = '''' OR UpdatedDate >= ''' + cast (#DateFrom as varchar(99)) + ''')
AND (''' + cast (#DateTo as varchar(25)) + ''' = '''' OR UpdatedDate <= ''' + cast (#DateTo as varchar(99)) + ''')
ORDER BY
CASE WHEN '''+ #OrderBy +'''=''ItemDescription'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''0'' THEN cteForPriceVen.ItemDescription END ASC,
CASE WHEN '''+ #OrderBy +'''=''ItemDescription'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''1'' THEN cteForPriceVen.ItemDescription END DESC,
CASE WHEN '''+ #OrderBy +'''=''ItemPartNumber'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''0'' THEN cteForPriceVen.ItemPartNumber END ASC,
CASE WHEN '''+ #OrderBy +'''=''ItemPartNumber'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''1'' THEN cteForPriceVen.ItemPartNumber END DESC,
CASE WHEN '''+ #OrderBy +'''=''Price'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''0'' THEN Price END ASC,
CASE WHEN '''+ #OrderBy +'''=''Price'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''1'' THEN Price END DESC,
CASE WHEN '''+ #OrderBy +'''=''UpdatedDate'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''0'' THEN UpdatedDate END ASC,
CASE WHEN '''+ #OrderBy +'''=''UpdatedDate'' AND '''+ cast (#OrderMode as varchar(10)) +'''= ''1'' THEN UpdatedDate END DESC'
Extracted Query:
;WITH
cteForPriceVen AS (select AI.ItemID, AI.ItemPartNumber as ItemPartNumber, AI.ItemDescription, cteForPrice.VendorPrice as Price, cteForPrice.UpdatedDate as UpdatedDate, cteForPrice.IsLocked as IsLocked
from AerospaceItems (nolock) AI
inner join VendorItemPricing (nolock) cteForPrice
on AI.ItemPartNumber = cteForPrice.ItemPartNumber where cteForPrice.VendorName = 'Apple' AND
cteForPrice.ObsoleteItem = '0') select * from cteForPriceVen
WHERE ('' = '' OR cteForPriceVen.ItemDescription like '%%')
AND ('' = '' OR cteForPriceVen.ItemPartNumber like '%%')
AND ('' = '' OR Price >= '')
AND ('' = '' OR Price <= '')
AND ('' = '' OR UpdatedDate >= '')
AND ('' = '' OR UpdatedDate <= '')
ORDER BY
CASE WHEN 'ItemDescription'='ItemDescription' AND '0'= '0' THEN cteForPriceVen.ItemDescription END ASC,
CASE WHEN 'ItemDescription'='ItemDescription' AND '0'= '1' THEN cteForPriceVen.ItemDescription END DESC
If I remove second order by line, CASE WHEN 'ItemDescription'='ItemDescription' AND '0'= '1' THEN cteForPriceVen.ItemDescription END DESC the query seems working.
The second line:
CASE WHEN 'ItemDescription'='ItemDescription' AND '0'= '1' THEN cteForPriceVen.ItemDescription END DESC
Is equivalent to NULL. You can't order something by NULL.
edit
If this statement is being generated by a dynamic query, what you need to do is fix the way you build the dynamic query:
#orderQuery = ' ORDER BY '
IF #OrderBy = 'ItemDescription'
BEGIN
orderQuery += ' cteForPriceVen.ItemDescription '
orderQuery += CASE WHEN #OrderMode = 1 THEN 'ASC' ELSE 'DESC' END
END
This line just doesn't make sense:
CASE WHEN 'ItemDescription'='ItemDescription' AND '0'= '0'
shouldn't it be something like:
CASE WHEN variableName = 'Value' ...