Subquery inside a view is not working corectly - sql-server

Hey I am creating view to be used in FastReport(ReportingSoftware) and I have a sub-query in the form of a scalar-Valued Function inside this to pull together the full address of a property, Though it is bringing back the error Subquery returned more than 1 value and im not sure why, i have used something similar to this in the past cant seem to figure out the issue.
Here is my View Code
SELECT TOP (100) PERCENT dbo.PropertyMaster.PropertyID,
dbo.Lookup_PropertyManager.Description, dbo.Lookup_PropertyManager.Email,
dbo.GetFullAddress(dbo.PropertyMaster.PropertyID) AS FullAddress,
dbo.Tenants.TenantID, dbo.Tenants.LeaseID,
dbo.Tenants.TenantForeName + ' ' + dbo.Tenants.TenantSurname AS FullName,
dbo.PropertyMaster.SPMReference,
CONVERT(varchar, dbo.PropertyLease.StartDate,101) AS StartDate,
CONVERT(varchar, dbo.PropertyLease.DateSigned, 101) AS DateSigned
FROM dbo.PropertyLease
RIGHT OUTER JOIN dbo.PropertyMaster
ON dbo.PropertyLease.PropertyID = dbo.PropertyMaster.PropertyID
LEFT OUTER JOIN dbo.Tenants
ON dbo.PropertyMaster.PropertyID = dbo.Tenants.PropertyID
LEFT OUTER JOIN dbo.Lookup_PropertyManager
ON dbo.PropertyMaster.PropertyManagerID = dbo.Lookup_PropertyManager.PropertyManagerID
ORDER BY dbo.PropertyMaster.PropertyID
and here is my scalar-Valued Function
ALTER FUNCTION [dbo].[GetFullAddress]
-- Add the parameters for the function here
(#PropertyID as integer )
RETURNS varchar(250)
AS
BEGIN
DECLARE #AddressLine as varchar(40)
DECLARE #FullAddress as varchar(250)
SET #FullAddress = (SELECT LTRIM(ISNULL(TenantForeName + ' ', ' ') + TenantSurname) AS FullName FROM Tenants WHERE PropertyID = #PropertyID) + CHAR(10)
SET #AddressLine = (SELECT ISNULL(AddressLine1, '') FROM PropertyMaster WHERE PropertyID = #PropertyID)
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
SET #AddressLine = (SELECT ISNULL(AddressLine2, '') FROM PropertyMaster WHERE PropertyID = #PropertyID)
IF #AddressLine <> ''
BEGIN
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
END
SET #AddressLine = (SELECT ISNULL(AddressLine3, '') FROM PropertyMaster WHERE PropertyID = #PropertyID)
IF #AddressLine <> ''
BEGIN
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
END
SET #AddressLine = (SELECT ISNULL(Town, '' ) FROM PropertyMaster WHERE PropertyID = #PropertyID)
IF #AddressLine <> ''
BEGIN
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
END
SET #AddressLine = (SELECT ISNULL(PostCode, '') FROM PropertyMaster WHERE PropertyID = #PropertyID)
SET #FullAddress = #FullAddress + #AddressLine
RETURN #FullAddress
END

The problem is most likely this line
SET #FullAddress = (SELECT LTRIM(ISNULL(TenantForeName + ' ', ' ') + TenantSurname) AS FullName FROM Tenants WHERE PropertyID = #PropertyID) + CHAR(10)
You can change it to just get the first tenant by adding Top 1
SET #FullAddress = (SELECT TOP 1 LTRIM(ISNULL(TenantForeName + ' ', ' ') + TenantSurname) AS FullName FROM Tenants WHERE PropertyID = #PropertyID) + CHAR(10)
Or you can concatenate all of the tenants together.
SELECT #FullAddress = COALESCE(#FullAddress, '')
+ LTRIM(ISNULL(TenantForeName + ' ', ' ') + TenantSurname) AS FullName
FROM Tenants
WHERE PropertyID = #PropertyID) + CHAR(10)
P.S. If this is the issue. Your view is most like returning duplicate rows since you are left joining to the tenants table also. If you need a row for each tenant in your view, then you'll probably want to pass in the tenantid to the function and add that as a where clause to the query to get the tenant name.

This is not an answer to the question.
I'm posting it here only since it's almost impossible to read code posted in comments.
In addition to what user1221684 wrote in his/hers answer,
The rest of the function can be written like this:
SELECT #FullAddress = #FullAddress + CHAR(10) +
ISNULL(AddressLine1 + CHAR(10), '') +
ISNULL(AddressLine2 + CHAR(10), '') +
ISNULL(AddressLine3 + CHAR(10), '') +
ISNULL(Town + CHAR(10), '' ) +
ISNULL(PostCode, '')
FROM PropertyMaster WHERE PropertyID = #PropertyID
Explanation:
There really is no need to select a different column from the same table
in more then one query.
In sql server, when you concatenate a string (char(10) in this case) to a null value, the result is null. therefor ISNULL(AddressLine1 + CHAR(10), '') would return an empty string if AddressLine1 is null.

Related

Using change tracking on a table that has his records constantly deleted and re-inserted

I'm building a layer over an application that needs to catch the changes happens to the data and update another system with these changes (SIF) and I faced a problem with a specific table, the application truncates the table, and insert a new set of records every time the data reconciled.
In order to solve this problem, I used a shadow table and Merged the records from the original table, and as I found that I might use the same method with other tables in the future, I created a generic SP that reads the structure of the tow tables and constructs a merge statement then runs it and I'm sharing the SP in the first answer, hope someone makes use of it, any comment or question is welcomed.
The SP works as long as the two tables are identical and the change tracking is working beautifully.
1- Creating the SP
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [Compare2Tables](
#DestSchema as NVarchar(255) ,
#DestTable as NVarchar(255),
#SrcSchema as NVARCHAR(255) ,
#srcTable as NVARCHAR(255) ,
#AdditionalCondition as NVARCHAR(MAX)
)
AS
BEGIN
DECLARE #JoiningFields as NVARCHAR(MAX)
DECLARE #MismatchingCondition as NVARCHAR(MAX)
DECLARE #UpdateOtherFields as NVARCHAR(MAX)
DECLARE #InsertDestFields as NVARCHAR(MAX)
DECLARE #InsertSrcFilds as NVARCHAR(MAX)
DECLARE #TheSQL as NVARCHAR(MAX)
DECLARE #CurrentColumn as NVARCHAR(255)
DECLARE #CurrentConstraint as NVARCHAR(255)
DECLARE #tablespecs TABLE (
TABLE_SCHEMA nvarchar(255) ,
TABLE_NAME nvarchar(255) ,
COLUMN_NAME nvarchar(255) ,
CONSTRAINT_NAME nvarchar(255)
)
insert into #tablespecs SELECT DISTINCT T.TABLE_SCHEMA , T.TABLE_NAME , T.COLUMN_NAME ,CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.COLUMNS t
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE K ON T.TABLE_NAME = K.TABLE_NAME AND T.TABLE_SCHEMA = K.TABLE_SCHEMA AND T.COLUMN_NAME = K.COLUMN_NAME
WHERE T.TABLE_NAME = #DestTable
AND T.TABLE_SCHEMA = #DestSchema
set #JoiningFields = ' '
set #MismatchingCondition = ' '
set #UpdateOtherFields = ' '
set #InsertDestFields = ' '
set #InsertSrcFilds = ' '
while exists (select * from #tablespecs)
Begin
set #CurrentColumn = (Select top 1 Column_name from #tablespecs)
--select #CurrentColumn
Set #CurrentConstraint = (Select CONSTRAINT_NAME FROM #tablespecs WHERE COLUMN_NAME = #CurrentColumn)
if not #CurrentConstraint is null
set #JoiningFields = #JoiningFields + ' D.' + #CurrentColumn + '=S.' + #CurrentColumn + ' AND '
ELSE
begin
SET #MismatchingCondition = #MismatchingCondition + ' ISNULL(D.' + #CurrentColumn + ',0) <> ISNULL(S.' + #CurrentColumn + ',0) OR '
SET #updateOtherFields = #updateOtherFields + 'D.' +#CurrentColumn + ' = S.' + #CurrentColumn + ','
end
set #InsertDestFields = #InsertDestFields + #CurrentColumn + ','
set #InsertSrcFilds = #InsertSrcFilds + 'S.' + #CurrentColumn + ',';
delete from #tablespecs where Column_Name = #CurrentColumn
End
SET #JoiningFields = SUBSTRING(#JoiningFields , 1 , len(#JoiningFields) - 4)
SET #MismatchingCondition = SUBSTRING(#MismatchingCondition , 1 , len(#MismatchingCondition) - 3)
SET #UpdateOtherFields = SUBSTRING(#UpdateOtherFields , 1 , len(#updateOtherFields) - 1)
SET #InsertDestFields = SUBSTRING(#InsertDestFields , 1 , len(#InsertDestFields) - 1)
SET #InsertSrcFilds = SUBSTRING(#InsertSrcFilds , 1 , len(#InsertSrcFilds) - 1)
--select #JoiningFields JoiningFields , #UpdateOtherFields UpdateOtherFields , #MismatchingCondition MismatchingCondition , #InsertDestFields InsertDestFields , #InsertSrcFilds InsertSrcFilds
set #TheSQL = 'MERGE INTO ' + #DestSchema + '.' + #DestTable + ' AS D using (SELECT * FROM ' + #SrcSchema+'.'+ #SrcTable + ' ' + #AdditionalCondition + ') AS S ON ' + #JoiningFields + ' WHEN MATCHED AND (' + #MismatchingCondition + ')
THEN UPDATE SET ' + #updateOtherFields + '
WHEN NOT MATCHED BY TARGET THEN
INSERT (' + #InsertDestFields + ')
VALUES (' + #InsertSrcFilds + ')
WHEN NOT MATCHED BY SOURCE THEN
DELETE;'
EXECUTE sp_executesql #TheSQL
END
2- Now see the implementation
--Create theSource table
CREATE TABLE TheSource
(
TheID INT PRIMARY KEY,
TheName VARCHAR(100),
TheCost MONEY,
ProductionYear VARCHAR(4)
)
GO
--Fill some records in TheSource
INSERT INTO TheSource
VALUES
(1, 'Word', 10.00,'2018'),
(2, 'Access', 20.00,'2018'),
(3, 'Excel', 30.00,'2017'),
(4, 'PowerPoint', 40.00,'2017')
GO
--Create Destination table
CREATE TABLE TheDest
(
TheID INT PRIMARY KEY,
TheName VARCHAR(100),
TheCost MONEY,
ProductionYear VARCHAR(4)
)
GO
--The Dest table is left with no records on purpose
SELECT * FROM TheSource
SELECT * FROM TheDest
GO
--The folloing syntax will fill only products of 2017
execute [Compare2Tables] 'dbo','TheDest','dbo', 'TheSource','Where ProductionYear = 2017'
SELECT * FROM TheDest
-- Syncronizing all records regardless of the year
execute [Compare2Tables] 'dbo','TheDest','dbo', 'TheSource',' '
SELECT * FROM TheDest
--Updating one row in the source, then sync
update TheSource set TheCost = 33.00 where TheName = 'Access'
execute [Compare2Tables] 'dbo','TheDest','dbo', 'TheSource',' '
SELECT * FROM TheDest
-- updating all records in the source, then sync
update TheSource set TheCost = TheCost * 0.75
execute [Compare2Tables] 'dbo','TheDest','dbo', 'TheSource',' '
SELECT * FROM TheDest

Add WHERE conditions dynamically

I'm trying to replicate a crystal report with a dynamic parameter. If I type a string into the parameter screen and click the arrow button, it adds the parameter to a list:
The resulting query looks like this, but the list can grow with additional OR #param clauses:
SELECT * FROM table_name WHERE #param LIKE 'cfe%' OR #param LIKE 'abr%'
How can I create a list like that in SSRS to contain several parameters? The query below is one possible example:
SELECT * FROM table_name WHERE
#param LIKE 'cfe%'
OR #param LIKE 'abr%'
OR #param LIKE 'fez%'
OR #param LIKE 'zez%'
I tried using multiple values in the parameter, but as soon as I do I can't type in the parameter box:
I tried this but it did not work. I also tried to use CONTAINS but there are no indexes for a view.
You can use a single parameter string. The user separates entries in the list with a comma. The query got a lot worse though but I have you an example of variable number of prefixes with comma separated.
I hope this helps. Its not as simple or as pretty.
In the dataset, use a similar query or proc that uses the parameter like so and it should work:
Declare #prefixes varchar(1000)
set #prefixes='abc,defg,efgh,hij,jkl,mno'
declare #sql nvarchar(max) = ''
declare #currentint int
set #currentint = 1
declare #maxint int
set #maxint = len(#prefixes) - len(replace(#prefixes, ',', '')) + 1
declare #currentcommaposition int
set #sql = 'IF OBJECT_ID(''tempdb..#tempTest'') IS NOT NULL DROP TABLE #tempTest
create table #tempTest
(
ID INT,
name varchar(100)
)
insert into #tempTest
(id,name)
select 1,''abcd''
union
select 2, ''defghijk''
union
select 3,''efghoot''
union
select 4,''hijack''
union
select 5,''jklmo''
union
select 6,''mnopoly''
union
select 7,''pqrstuv''
union
select 8,''tubool''
IF OBJECT_ID(''tempdb..#testresults'') IS NOT NULL DROP TABLE #testresults
create table #testresults
(
id int, name varchar(100)
)
declare #prefixes varchar(100) = ''' + #prefixes + ',''' + char(10) + ' declare #currentint int declare #maxint int = ' + convert(varchar(10),#maxint) + char(10)
while ( #currentint <= #maxint )
begin
set #sql = #sql + 'set #currentint = ' + convert(varchar(10),#currentint) + ' declare #suffix' + convert(varchar(2), #currentint) + ' VARCHAR(100)' + char(10)
+ 'set #suffix' + convert(varchar(2), #currentint) + '= substring(#prefixes,0,charindex('','',#prefixes))' + char(10)
+
'set #prefixes=Right(#prefixes,len(#prefixes)-charindex('','',#prefixes))' + char(10) +
'insert into #testresults (id, name)
select id, name from #temptest t where t.name like #suffix' + convert(varchar(2), #currentint) + ' + ''%''' + char(10)
+ 'if (#currentint = #maxint) begin select * from #testresults end ' + char(10)
set #currentint = #currentint + 1
end
exec sp_executesql #sql
The second option for you will be having parameters for each suffix a user can answer and allow them to be blank or null as the default. This will limit the number of prefixes the user can enter, but I do think you should be able to guesstimate the max number a user would enter. Or the user can run the report multiple times and when they do they export to excel to mash the reports together if they want to.
This is a bit easier to understand for the developer but more work for the user.
So in your stored procedure you will then use a statement like below:
select *
from dbo.Test t
WHERE
( ISNULL(#Prefix1,'') <> '' AND t.TestName LIKE #Prefix1 + '%')
OR
( ISNULL(#Prefix2,'') <> '' AND t.TestName LIKE #Prefix2 + '%')
OR
( ISNULL(#Prefix3,'') <> '' AND t.TestName LIKE #Prefix3 + '%')
OR
( ISNULL(#Prefix4,'') <> '' AND t.TestName LIKE #Prefix4 + '%')
OR
( ISNULL(#Prefix5,'') <> '' AND t.TestName LIKE #Prefix5 + '%')
OR
( ISNULL(#Prefix6,'') <> '' AND t.TestName LIKE #Prefix6 + '%')
OR
( ISNULL(#Prefix7,'') <> '' AND t.TestName LIKE #Prefix7 + '%')
OR
( ISNULL(#Prefix8,'') <> '' AND t.TestName LIKE #Prefix8 + '%')
OR
( ISNULL(#Prefix9,'') <> '' AND t.TestName LIKE #Prefix9 + '%')
OR
( ISNULL(#Prefix10,'') <> '' AND t.TestName LIKE #Prefix10 + '%')

SQL Server: I am getting an error while altering view when I try to add some virtual column which in turn based on virtual column

I have 20 databases, each with same table but different columns.
So to make the uniform we are creating views on top of each table in a database which will contain all the columns, as there will be one application accessing all the database.
In the view, I have to write the query in such a way that if I want to alter it and add any addition column for testing I should be able to do that.
Now in below query I am altering / creating query such that it takes all the columns of that table from the database, and then I append the other columns which are not present in it.
I need to add a column which will just concatenate some of the columns
ALTER VIEW [dbo].[AIV_PARKING]
AS
SELECT
*,
Cast(NULL AS [VARCHAR](20)) [ACTCODE],
Cast(NULL AS [VARCHAR](1)) [ACTIVATEINFO],
Cast(NULL AS [VARCHAR](20)) [VEHLICNOCHECK],
Cast(NULL AS [VARCHAR](40)) [ACTIVITY],
Cast(Isnull(vehlicnocheck, '') + '|' +
Isnull(officername, '') + '|' +
Isnull(locstreet, '') + '|' +
Isnull(locsideofstreet, '') + '|' +
Isnull(loccrossstreet1, '') + '|' +
Isnull(loccrossstreet2, '') + '|'
+ Isnull(locsuburb, '') + '|'
+ Isnull(locstate, '') + '|'
+ Isnull(locpostalcode, '') + '|'
+ Isnull(loclot, '') + '|'
+ Isnull(locpostalcode, '') + '|'
+ Isnull(Cast(officerid AS VARCHAR(20)), '')
+ Isnull(officername, '') + '|'
+ Isnull(Cast (issueno AS VARCHAR(100)), '') AS NVARCHAR(max)) AS SearchText
FROM
[dbo].parking
Here I added a column called SearchText which concatenates other columns, but I get an error
Invalid column name 'VehLicNoCheck'
Is there any way I can add this column to this view?
I also tried to do to something below but I got the same error:
CAST(CASE
WHEN NOT EXISTS
(
Select 1 from INFORMATION_SCHEMA.COLUMNS
Where Column_name ='VehLicNoCheck'
and table_name='Parking'
)
THEN ''
ELSE ISNULL(VehLicNoCheck,'')
END as nvarchar(max)
)
you could create a view that normalizes the uncommon columns to rows, where the values for the common columns are just repeated, e.g:
select id, col, value from parking
unpivot (value for col in (actcode, vehLicNoCheck, etc.)) x
the code to dynamically generate the view would be something like:
declare #sql varchar(max) = 'select id, col, value from parking unpivot (value for col in ('
select #sql += quotename(name) +',' from sys.columns where object_id=object_id('parking') and name not in ('id')
set #sql = substring(#sql, 1, len(#sql) - 1) + '))x'
exec(#sql)
this does not make sense at all.
the [ACTCODE], [ACTIVATEINFO] are all NULL value
so basically SearchText is just a string of '|||||'
you might as well, just do this
SELECT *,
CAST( NULL AS varchar) [ACTCODE],
CAST( NULL AS varchar) [ACTIVATEINFO],
CAST( NULL AS varchar) [VEHLICNOCHECK],
CAST( NULL AS varchar) [ACTIVITY],
'||||||' as SearchText
FROM [dbo].PARKING
Maybe if you can explain what are you trying to achieve here, we can point you to the right direction
EDIT :
You will need to use Dynamic SQL. You will need a list of all column names
-- declare a table variable for all the columns that you required
declare #columns table
(
id int identity,
name varchar(100)
)
-- for example these are the required columns
insert into #columns
values ('ACTCODE'), ('ACTIVATEINFO'), ('VEHLICNOCHECK'), ('ACTIVITY')
-- The Query to create the view
declare #sql nvarchar(max)
select #sql = N'CREATE VIEW [AIV_PARKING] AS' + char(13) + 'SELECT' + char(13)
select #sql = #sql
+ case when t.name is not null
then quotename(c.name) + ','
else 'CAST (NULL AS VARCHAR(10)) AS ' + quotename(c.name) + ','
end
+ char(13)
from #columns c
left join sys.columns t on c.name = t.name
and t.object_id = object_id('PARKING')
order by c.id
select #sql = #sql
+ case when t.name is not null
then 'ISNULL(' + quotename(c.name) + ', '''')'
else ''
end
+ ' + ''|'''
+ ' + '
from #columns c
left join sys.columns t on c.name = t.name
and t.object_id = object_id('PARKING')
order by c.id
select #sql = left(#sql, len(#sql) - 8) + ' AS SearchText' + char(13)
+ 'FROM PARKING'
-- print out to view the complete create view statement
print #sql
-- execute it
exec sp_executesql #sql

SQL query calling user defined function issue

I have the following SQL query in stored procedure and trying to call Table-value function(fn_get_type_ids). I am getting 'Must declare the scalar variable "#category_id".' error message. Table-value function returns muliple IDs. How do I call this function?
The stored procedure works if I pass hard coded values to the function.
dbo.fn_get_type_ids(2, 90, NULL). It doesn't work if I pass variables shown below. What could be wrong? please suggest.
ALTER PROCEDURE [dbo].[get_search_results]
#user_id BIGINT,
#category_id INT = NULL,
#a_id INT = NULL,
#all_detail_id INT = NULL
AS
BEGIN
DECLARE #select_list VARCHAR(4000)
DECLARE #where_condition VARCHAR(4000)
SELECT #select_list = 'SELECT DISTINCT c.table1_id, c.table1_number, c.type_id '
SELECT #select_list = #select_list + ' FROM dbo.TABLE1 c '
SELECT #select_list = #select_list + ' LEFT JOIN TABLE2 cb ON cb.table1_id = c.table2_id '
SELECT #where_condition = ' WHERE c.active_flag = 1'
SELECT #where_condition = #where_condition + ' AND c.type_id in
(select type_id from dbo.fn_get_type_ids(#category_id, #a_id, #all_detail_id)) '
END
You are using dynamic sql and sql variables exist in different sessions, to make it work you need to change it to:
SELECT #where_condition = #where_condition + ' AND c.type_id in
(select type_id from dbo.fn_get_type_ids('+CAST(#category_id as varchar))+',
'+CAST(#a_id as varchar))+', '+CAST(#all_detail_id as varchar))+')) '
Try making that last select:
SELECT #where_condition = #where_condition + ' AND c.type_id in
(select type_id from dbo.fn_get_type_ids(' + ISNULL(#category_id,'NULL') + ', ' + ISNULL(#a_id,'NULL') + ', ' + ISNULL(#all_detail_id,'NULL') + ')) '

Dynamic Column Name and Value into Where clause

I have a procedure that I working on and I don't know what's going wrong. I have reviewed all other sites and could not find the issue that I'm having
I want to create procedure that has a dynamic where clause base on a combination of bits being sent to the procedure. I don't want to have to create a bunch of similar procedures because they have slightly different conditions.
I'm placing the below query into a cursor then looping through the cursor. Please help.
CREATE PROCEDURE [dbo].[procContainTest] (
#USE_A BIT,
#USE_B BIT,
#ValueA VARCHAR(50),
#ValueB VARCHAR(50),
#USERID VARCHAR(50)
)
AS
DECLARE #TEMP_Col1 INT,
#TEMP_Col2 INT,
#TEMP_Col3 VARCHAR(50),
#TEMP_Col4 VARCHAR(50),
#TEMP_Col5 VARCHAR(50),
#POINT_ONE NVARCHAR(50),
#POINT_TWO NVARCHAR(50)
SET #TRIGGER = 0
WHILE #TRIGGER = 0
BEGIN
-- F2 Booking Term
IF #USE_A = 1
AND #USE_B = 1
BEGIN
SET #POINT_ONE = 'ColName2'
SET #POINT_TWO = 'ColName3'
END
-- F6 Booking Term
IF #USE_A = 0
AND #USE_B = 1
BEGIN
SET #POINT_ONE = 'ColName1'
SET #POINT_TWO = 'ColName2'
END
DECLARE INNER_CURSOR CURSOR
FOR
SELECT TOP 1 TEMP_Col1 INT,
TEMP_Col2,
TEMP_Col3,
#TEMP_Col4,
#TEMP_Col5
FROM TEMP_Table
WHERE #POINT_ONE = + '''' + #ValueA + ''''
AND #POINT_TWO = + '''' + #ValueB + ''''
AND USERID = #USERID
ORDER BY LENGTH
l
You can put your Select Statmement in a variable like:
declare #YourSelectStatement nvarchar(max)
set #YourSelectStatement = ' SELECT TOP 1 TEMP_Col1 INT,
TEMP_Col2,
TEMP_Col3,
FROM TEMP_Table
WHERE ' + #POINT_ONE + '=' + #ValueA + '
AND ' + #POINT_TWO + '=' + #ValueB + '
AND USERID = ' + #USERID + '
ORDER BY LENGTH'
sp_executesql(#YourSelectStatement)
this is probably help you:
SELECT
id, first, last, email, notes
FROM
My_Table
WHERE
CASE ''''+#column_name_variable+''''
WHEN ''''+column_1+''''=1 THEN column_1
WHEN ''''+column_2+''''=2 THEN column_2
...
ELSE 'not null'
END IS NOT NULL
I would avoid the use of dynamic SQL altogether. You can eliminate your IF statements and embed the same logid in your SELECT statement like this:
SELECT TOP 1
TEMP_Col1,
TEMP_Col2,
TEMP_Col3,
TEMP_Col4,
TEMP_Col5
FROM TEMP_Table
WHERE (#USE_A = 1 AND #USE_B = 1 AND ColName2 = '''' + #ValueA + '''' AND ColName3 = '''' + #ValueB + '''')
OR (#USE_A = 0 AND #USE_B = 1 AND ColName1 = '''' + #ValueA + '''' AND ColName2 = '''' + #ValueB + '''')

Resources