SQL Query within VS TableAdapter Query Configuration Wizard - sql

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.

Related

How to optimize nested conditional SQL Server Query 2008R2

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

SQL with AND statements, dynamically building up

Aim: I'm building a dynamic SQL string and want to make the search an AND function
Code type: SQL stored procedure within SQL Server Management Studio
Issue: If the first search is not required then I need to know this (I know because the default is '0' in this case. I feel I'm missing a sitter but don't seem to be able to stackoverflow/Google for the solution.
I set up #QueryString with a default of '' so the functionality will work.
What will fix this?:
I've thought about COALESCE and potential use of IF ELSE within the IF but I am hoping there is clean solution along the lines of
SET #QUERYSTRING = IF(#QUERYSTRING = '','', + + ' FIELD1 LIKE ''%' + LTRIM(RTRIM(#s1)) + '%' )
Current example (snippet):
ALTER PROCEDURE [dbo].[spGridSearchTest]
#s1 NVARCHAR(20),
#s2 VARCHAR(20)
AS
BEGIN
DECLARE #QUERY NVARCHAR(MAX) = ''
DECLARE #QUERYSTRING NVARCHAR(MAX) = ''
SET #QUERY = 'SELECT * FROM TblTable'
IF #s1 <> '1234xyz'
SET #QUERYSTRING = #QUERYSTRING + ' Field1 LIKE ''%' + LTRIM(RTRIM(#s1)) + '%'
IF #s2 <> '1234xyz'
SET #QUERYSTRING = #QUERYSTRING + ' Field2 LIKE ''%' + LTRIM(RTRIM#s2)) + '%'
IF LEN(LTRIM(RTRIM(#QUERYSTRING))) > 0
SET #QUERY = LTRIM(RTRIM(#QUERY)) + ' WHERE ' + LTRIM(RTRIM(#QUERYSTRING)) + ''''
EXECUTE(#QUERY)
END
If I understand better your issue:
Try this:
ALTER PROCEDURE [dbo].[spGridSearchTest]
#s1 NVARCHAR(20),
#s2 VARCHAR(20)
AS
BEGIN
DECLARE #QUERY NVARCHAR(MAX) = ''
DECLARE #QUERYSTRING NVARCHAR(MAX) = ''
DECLARE #conditionadded char(1) = 'N'
SET #QUERY = 'SELECT * FROM TblTable'
IF #s1 <> '1234xyz'
BEGIN
SET #QUERYSTRING = ' Field1 LIKE ''%' + LTRIM(RTRIM(#s1)) + '%'
SET #conditionadded = 'Y'
END
IF #s2 <> '1234xyz'
BEGIN
IF (#conditionadded = 'Y')
BEGIN
SET #QUERYSTRING = #QUERYSTRING + ' AND '
END
SET #QUERYSTRING = #QUERYSTRING + ' Field2 LIKE ''%' + LTRIM(RTRIM#s2)) + '%'
SET #conditionadded = 'Y'
END
IF (#conditionadded = 'Y')
BEGIN
SET #QUERY = LTRIM(RTRIM(#QUERY)) + ' WHERE ' + LTRIM(RTRIM(#QUERYSTRING)) + ''''
END
EXECUTE(#QUERY)
END
Do you really need a dynamic query? Why not use something like this:
select
Whatever
from MyTable
where
(#s1 = '1234xyz' or Field1 = #s1)
and
(#s2 = '1234xyz' or Field2 = #s2)
This avoids a security hole, and depending on your query patterns and data set, it might even be faster. And of course, it's pretty easy to read, and you don't have to deal with SQL in strings :)

Dynamic sql with CASE expression

SET #SQL =
'SELECT
CaseStatus =
CASE Level1Status
WHEN 1100 THEN ''Case Submitted to QC''
WHEN 1200 THEN ''Pending QC''
WHEN 1400 THEN ''Passed QC''
END,
I'm currently having problems with the dynamic sql/case expression above , as I can't seem to put strings inside dynamic sql, does anyone happen to have a solution to fixing this
EDIT
AS
BEGIN
DECLARE #SQL nvarchar(4000)
SET #SQL =
'SELECT
CaseStatus =
CASE Level1Status
WHEN 1100 THEN ''Case Submitted to QC''
WHEN 1200 THEN ''Pending QC''
WHEN 1400 THEN ''Passed QC''
END,
CaseStartDateTime,
CaseEndDateTime,
StatusName,
Cell_NameDescription,
QCAnalystName,
AnalystName,
Upload_Datetime,
Requesting_Entity,
Legal_Entity_TypeDescription,
HighPriorityDescription,
DD_Level_RequiredDescription,
CountryDscr,
Maintable.KYCCaseId AS KYCCaseId
FROM
UACTc75760ab10784b51b585f082d4b25223 AS MI,
UACT175e55161660402692a53a4cdeb89bd6 AS MainTable,
UACT5996d6e5151245cab24e4e76e3e53540 AS Statuses,
UACTde5f05df6c5f4872a1e57b3cf8368301 AS AddressDetails
WHERE
(
MI.CaseStartDateTime BETWEEN ' + quotename(convert(varchar(10), #CaseStartDateTime, 120), '''') + ' AND ' + quotename(convert(varchar(10), #CaseEndDateTime, 120), '''') +
' OR
MI.CaseEndDateTime BETWEEN ' + quotename(convert(varchar(10), #CaseStartDateTime, 120), '''') + ' AND ' + quotename(convert(varchar(10), #CaseEndDateTime, 120), '''') +
' )
AND
MI.KYCCase_Id = MainTable.KYCCaseId'
IF #StatusName IS NOT NULL AND ltrim(rtrim(#StatusName)) != N''
SET #SQL = #SQL + '
AND
Statuses.SourceStatus = MainTable.Level1Status
AND
Statuses.StatusName = ' + quotename(#StatusName, '''')
IF #CountryDscr IS NOT NULL AND ltrim(rtrim(#CountryDscr)) != N''
SET #SQL = #SQL + '
AND
AddressDetails.CountryDscr = ' + quotename(#CountryDscr, '''')
IF #CellDscr IS NOT NULL AND ltrim(rtrim(#CellDscr)) != N''
SET #SQL = #SQL + '
AND
MainTable.Cell_NameDescription = ' + quotename(#CellDscr, '''')
IF #QCAnalystName IS NOT NULL AND ltrim(rtrim(#QCAnalystName)) != N''
SET #SQL = #SQL + '
AND
MainTable.QCAnalystName = ' + quotename(#QCAnalystName, '''')
IF #AnalystName IS NOT NULL AND ltrim(rtrim(#AnalystName)) != N''
SET #SQL = #SQL + '
AND
MainTable.AnalystName = ' + quotename(#AnalystName, '''')
IF #RequestingEntity IS NOT NULL AND ltrim(rtrim(#RequestingEntity)) != N''
SET #SQL = #SQL + '
AND
MainTable.Requesting_Entity = ' + quotename(#RequestingEntity, '''')
IF #EntityType IS NOT NULL AND ltrim(rtrim(#EntityType)) != N''
SET #SQL = #SQL + '
AND
MainTable.Legal_Entity_TypeDescription = ' + quotename(#EntityType, '''')
IF #HighPriority IS NOT NULL AND ltrim(rtrim(#HighPriority)) != N''
SET #SQL = #SQL + '
AND
MainTable.HighPriorityDescription = ' + quotename(#HighPriority, '''')
IF #DDLevelRequired IS NOT NULL AND ltrim(rtrim(#DDLevelRequired)) != N''
SET #SQL = #SQL + '
AND
MainTable.DD_Level_RequiredDescription = ' + quotename(#DDLevelRequired, '''')
EXEC sp_executesql #SQL
This is the entire code, The error I'm getting is
Msg 156, Level 15, State 1, Line 32
Incorrect syntax near the keyword 'Case'.
This is working fine .
Create Table #Level1Status(Id int identity ,Level1Status int)
Insert INto #Level1Status(Level1Status) values(1100),(1200),(1400)
Declare #SQL Nvarchar(Max)
SET #SQL =
'SELECT
CaseStatus =
CASE Level1Status
WHEN 1100 THEN ''Case Submitted to QC''
WHEN 1200 THEN ''Pending QC''
WHEN 1400 THEN ''Passed QC''
END from #Level1Status';
Exec SP_ExecuteSQL #SQL
Since you are concatenate your #SQL string with local variable "#xxx", in case any of thease may null, It want give any output so use ISNULL() or COALESCE() at concatenation with all local vaiable you used.

Dynamic sql stored procedure update query issue?

I've written the below code to set filepath column in my table as 'F:\DataMigration\Wise\DELTA_20121008\Attachments\SR\SR_1.txt'
where SR_1 is file_name column
.txt is file_ext column from my table.
but after executing following procedure, I'm getting filepath column in table as
'F:\DataMigration\Wise\DELTA_20121008\Attachments\file_name.file_ext'
means It's treating column names as string, how i can make it as column so it will
use values in that column.
alter procedure [dbo].[WISEMissingAttachmentReportGenerator]
(
#tablename varchar(255), #pathonlocal nvarchar(255)
)
as
begin
--step 1
exec dbo.proc_alter_table #tablename
--step 2
EXEC ('update '+ #tablename +
' set filepath = '''+ #pathonlocal + ' file_name'+'.'+'file_ext''')
EXEC('Select * from '+#tablename)
end
exec [dbo].[WISEMissingAttachmentReportGenerator] [WISE.Non_VP_Service_Request_Attachments_File_Check_Analysis],
N'F:\DataMigration\Wise\DELTA_20121008\Attachments\SR\'
Try;
EXEC('UPDATE '+ #tablename +
' SET filepath = '''+ #pathonlocal + ''' + file_name + '''+'.'+''' + file_ext')
Equal as;
UPDATE [YourTable] SET filepath = 'YourPath' + file_name + '.' + file_ext
Try changing your statement to this:
EXEC ('update '+ #tablename +
' set filepath = '''+ #pathonlocal + ''' + file_name + ''.'' + file_ext')
declare #tblnm varchar(20) = 'test'
declare #upda varchar(20) = 'update '
declare #set varchar(25) = ' set'
declare #id varchar(25) = ' id'
declare #cmd varchar(1000)
set #cmd = #upda + #tblnm + #set + #id + '=7'
exec(#cmd)
SAMPLE SQL UPDATE QUERY - FOR BUILDING TABLENAME DYNAMICALLY
EXECUTED GUYS - THIS IS CALL JUGAAAAAAAAAD [NO NEED TO GET INTO ''' STUFF]

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