How to optimize nested conditional SQL Server Query 2008R2 - sql

if {condition1} = '0'
begin
if {condition2} = 'Yes'
Begin
Set #SQLQuery = #SQLQuery + ' AND '
end
else
begin
Set #SQLQuery = #SQLQuery + ' AND '
end
end

As #Pranav states in the comments, you can do the following:
if {condition1} = '0'
Set #SQLQuery = #SQLQuery + ' AND ' +
CASE WHEN {condition2} = 'Yes' THEN <whatever cond2=Yes>
ELSE <whatever cond2<>Yes> END

hope this helps, just assign any or empty value to #SQLQuery before running this
SELECT #SQLQuery+ = CASE WHEN CONDITION1='0' AND CONDITION2='Yes' THEN
' AND '
WHEN CONDITION1='0' THEN
' AND '
END

Related

How to update table with while loop in Stored Procedure?

I want to update my dynamic table in while loop.
Here is my code:
While (#j<=#tmp_getRowCount)
Begin
Set #firstcolumn = (Select SplitFirst_tblAR from #result_AR Where rownumber = #j) //String//
Set #secondcolumn = (Select EMail_tblAR from #result_AR Where rownumber = #j) //String//
Set #thirdcolumn = (Select SplitFirst_tblKul from #result_AR Where rownumber = #j) //String//
Set #fourthcolumn = (Select EMail_tblKul from #result_AR Where rownumber = #j) //String//
insert into #test Values(#tmp_ID, #firstcolumn,#secondcolumn,#thirdcolumn,#fourthcolumn)
if ((#firstcolumn = #thirdcolumn) AND (#secondcolumn != #fourthcolumn) AND (#firstcolumn != ''))
begin
Set #q_updateTable = 'Update '+ quotename(#tablename) +' Set '+#columnname+' = ''' + #fourthcolumn + ''' Where ID = ' + #tmp_ID + ''
Exec sp_executesql #q_updateTable
end
SET #j = #j+1
End
My result_AR table:
I know the error is in here:
Where ID = ' + #tmp_ID + ''
When I change this Where clause as,
Where '+#columnname+' = ''' + #secondcolumn + ''' '
code works correctly.
Why can't I set as ID my where clause? I am getting ID value as integer.
The error is 'Query completed with errors'.
Thanks in advance.
you can not set Id in where clause because the id is integer value and you are concatenating it with string (varchar).
So first you have to convert it in (String)varchar and the you can use it where clause.
Like :
Set #q_updateTable = 'Update '+ quotename(#tablename) +' Set '+#columnname+' = ''' + #fourthcolumn + ''' Where ID = ' + convert(varchar,#tmp_ID) + ''
Exec sp_executesql #q_updateTable
you have to use "convert(varchar,#tmp_ID)" insted of "#tmp_ID"

Dynamic query SQL where condition

I want to attach numeric value in dynamic query but I am an getting error:
Conversion failed when converting the varchar value ' + #psRegionCode + ' to data type smallint
My query is:
SET #psRegionCode = UPPER(LTRIM(RTRIM(#psRegionCode)))
IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr + ' ' + 'AND reg.region_cd = ''' + #psRegionCode + ''''
END
Things which I tried:
SET #psRegionCode = UPPER(LTRIM(RTRIM(#psRegionCode)))
IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr + ' ' +
'AND reg.region_cd = ' + cast(#psRegionCode as nvarchar(10) ''
END
Can somone please help me with this?
IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr +
' AND reg.region_cd = ' + cast(#psRegionCode as nvarchar(10))
you need to make sure you have correct number of apostrophes
if #psRegionCode is number, why you ltrim it? if it is a string why you cast it?
Well, by your syntax I'm guessing SQL-Server? Any way I think your second query should work, you are just missing a parenthesis :
IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr +
' AND reg.region_cd = ' + cast(#psRegionCode as nvarchar(10))
END
You can't concat a number into a string without the conversion.

MS SQL Stored Procedure run time error

How to rectify error in sp while concatenating the MSSQL queries?
SET #Ws_Sql = 'SELECT CONVERT(VARCHAR(25),#WS_STATUS) AS [Status],A.RECNUB AS [Rec #], A.REVCOD AS [Revenue CODE], '
IF #LNKOPT = 1
BEGIN
SET #Ws_Sql = #WS_SQL +''' AS [Status],'
END
ELSE IF #LNKOPT = 2
BEGIN
SET #Ws_Sql = #WS_SQL +'' + 'Modified' + ' AS [Status],'
END
ELSE IF #LNKOPT = 3
BEGIN
SET #Ws_Sql = #WS_SQL +'' + 'Deleted' + ' AS [Status],'
END
ELSE IF #LNKOPT = 4
BEGIN
SET #Ws_Sql = #WS_SQL +'' + 'Reprint' + ' AS [Status],'
END
Are you attempting to assign an empty value to the [Status] output column, in case #LNKOPT = 1?
In that case, you need to use double apostrophes, to escape the apostrophe character:
IF #LNKOPT = 1
BEGIN
SET #Ws_Sql = #WS_SQL +''''' AS [Status],'
END
which will result in #Ws_Sql containing: '' AS [Status] (otherwise it would result in ' AS [Status] which will give an error when the #Ws_Sql string is executed).

How can I use single quote inside sql command? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I escape a single quote in sqlserver?
I got a script below that drop everything on the database from this link. It does error when I execute on this line.
SET #statement = '
IF(#type = 'F') or (#type = 'C') or (#type = 'D') or (#type='F') or (#type='K')
The reason is because the single quote. I want to know how can I fix this error?
/*** drop (pretty much) everything before rebuilding the database ***/
DECLARE
OBJECTS CURSOR FOR SELECT
so.name,
so.type,
so.type_desc,
p.name AS parentName
FROM
sys.objects AS so
LEFT JOIN sys.objects AS p ON so.parent_object_id = p.object_id
WHERE
so.schema_id = 1
ORDER BY
CASE
WHEN so.type = 'F' THEN
0
WHEN so.type = 'TR' THEN
1
WHEN so.type = 'U' THEN
2
WHEN so.type = 'F' THEN
3
ELSE
4
END OPEN OBJECTS DECLARE
#name AS nvarchar (MAX) DECLARE
#type AS nvarchar (2) DECLARE
#type_desc AS nvarchar DECLARE
#parentName AS nvarchar (MAX) DECLARE
#statement AS nvarchar (MAX) FETCH NEXT
FROM
OBJECTS INTO #name,
#type,
#type_desc,
#parentName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #statement = ' IF(#type = ' F ')
BEGIN
PRINT ' DROPING FK : ' + #name + ' OF type ' + #type + ' (' + #type_desc + ') '
SET #statement = ' ALTER TABLE ' + #parentName + ' DROP CONSTRAINT ' + #name
EXECUTE(#statement)
END
ELSE IF (#type = ' TR ')
BEGIN
PRINT ' DROPING TRIGGER : ' + #name + ' OF type ' + #type + ' (' + #type_desc + ') '
SET #statement = ' DROP TRIGGER ' + #name
EXECUTE(#statement)
END
ELSE IF (#type = ' U ')
BEGIN
PRINT ' DROPING TABLE : ' + #name + ' OF type ' + #type + ' (' + #type_desc + ') '
SET #statement = ' DROP TABLE ' + #name
EXECUTE(#statement)
END
ELSE IF (#type = ' FN ')
BEGIN
PRINT ' DROPING FUNCTION : ' + #name + ' OF type ' + #type + ' (' + #type_desc + ') '
SET #statement = ' DROP FUNCTION ' + #name
EXECUTE(#statement)
END
ELSE
PRINT ' Didn 't drop object ' + #name + ' of type ' + #type + ' (' + #type_desc + ')' FETCH NEXT
FROM
OBJECTS INTO #name,
#type,
#type_desc,
#parentName
END CLOSE OBJECTS DEALLOCATE OBJECTS
if you want to use single quote inside a prepared statement, escape it with another single quote, example,
SET #statement = 'world''s view';
SET #statement2 = 'world''s view';
from your example above
SET #statement = '
IF(#type = ''F'') or (#type = ''C'') or
(#type = ''D'') or (#type=''F'') or
(#type=''K'')'
-- the strings are all red.
Single quote is used to represent a string literal in SQL.
If you need to explicitly insert a single quote , you should use double single quotes ('')
It should be like this:
SET #statement = 'IF(#type = ''F'') or (#type = ''C'') or (#type = ''D'') or (#type=''F'') or (#type=''K'')'
Raj

SQL Query within VS TableAdapter Query Configuration Wizard

I am trying to write an SQL query within Visual Studio TableAdapter Query Wizard
My SQL query is:
DECLARE #SQL varchar(255);
SET #SQL = ' SELECT * FROM dbAddress WHERE 1 = 1'
IF #ApexLine1 = ''
BEGIN
SET #SQL = #SQL + ' AND addLine1 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine1 = ''' + #ApexLine1 + ''''
END
IF #ApexLine2 = ''
BEGIN
SET #SQL = #SQL + ' AND addLine2 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine2 = ''' + #ApexLine2 + ''''
END
IF #ApexLine3 = ''
BEGIN
SET #SQL = #SQL + ' AND addLine3 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine3 = ''' + #ApexLine3 + ''''
END
IF #ApexZip = ''
BEGIN
SET #SQL = #SQL + ' AND addPostCode IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addPostCode = ''' + #ApexZip + ''''
END
IF #ApexCity = ''
BEGIN
SET #SQL = #SQL + ' AND addLine4 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine4 = ''' + #ApexCity + ''''
END
IF #ApexProv = ''
BEGIN
SET #SQL = #SQL + ' AND addLine5 IS NULL '
END
ELSE
BEGIN
SET #SQL = #SQL + ' AND addLine5 = ''' + #ApexProv + ''''
END
EXEC(#SQL)
I get the error:
'The Declare SQL contruct or statement is not supported'
If I remove the Declare statement I get error:
'The Set SQL construct or statement is not supported'
Is there a work around for this?
Thanks.
Anything like this:
SET #SQL = #SQL + ' AND addLine1 = ''' + #ApexLine1 + ''''
is EVIL. Don't do it. Variables like #ApexLine1 could contain anything, even something like this:
';DROP TABLE dbAddress--
Think very carefully about what would happen if someone entered something like that in your Address Line 1 field. The only correct solution here is to use the built-in sp_executesql stored procedure. Learn it, use it.
Aside from that, I think at least part of your problem might be that your #SQL variable is only 255 characters. It's easily possible your query is running out of space.