How to write an sqlite query for the following scenario? [duplicate] - sql

This question already has answers here:
How to write the equivalent SQL case statement for query given below?
(2 answers)
Closed 8 years ago.
Here is my query for wpf form
Query = "select Cust_Id,Card_Number,Clients_Title,Address_Current,Phone_Number,Mobile_Number from Customer_New Where 1=1";
try
{
if (txt_title.Text != "")
Query += " and Clients_Title Like '%" + txt_title.Text + "%'";
if (txt_address.Text != "")
Query += " and Address_Current Like '%" + txt_address.Text + "%'";
if (txt_phone.Text != "")
Query += " and Phone_Number Like '%" + txt_phone.Text + "%'";
if (txt_mobile.Text != "")
Query += " and Mobile_Number Like '%" + txt_mobile.Text + "%'";
if (cbo_location.Text != "")
Query += " and AreaLocation Like '%" + cbo_location.Text + "%'";
}
catch { }
I want to report viewer query data like my wpf form .
Here is the query that i am trying in report viewer
SELECT Cust_Id, Clients_Title, Card_Number, Key_Person, Address_Current, Phone_Number, Mobile_Number, AreaLocation
FROM Customer_New
WHERE (Clients_Title = #Clients_Title) OR
(Address_Current = #Address_Current) OR
(Phone_Number = #Phone_Number) OR
(Mobile_Number = #Mobile_Number) OR
(AreaLocation = #AreaLocation)
Can anyone tell me query for report viewer like wpf form .
Note :-
I cant use cant use C# controls in report viewer.Here in report
viewer i can only use sql
What is needed in report viewers query is:
When are all string of where clause are null then my report viewer
should select query is:
Query = "select Cust_Id,Card_Number,Clients_Title,Address_Current,Phone_Number,Mobile_Number from Customer_New ";
When any two string of where clause are not matching corresponding
row db then nothing
will be displayed
Lastly, selection will be made if just one condition of where clause
is provided

SELECT Cust_Id, Clients_Title, Card_Number, Key_Person, Address_Current, Phone_Number, Mobile_Number, AreaLocation
FROM Customer_New
where (CASE
WHEN #Clients_Title != '' THEN Clients_Title=#Clients_Title
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #Address_Current != '' THEN Address_Current =#Address_Current
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #Phone_Number != '' THEN Phone_Number=#Phone_Number
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #Mobile_Number != '' THEN Mobile_Number=#Mobile_Number
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #AreaLocation != '' THEN AreaLocation =#AreaLocation
ELSE
NULL IS NULL
END)

Related

How to insert if statement in sql query at vb.net?

How to insert if/else in the query?
This is my sqlcommand query :
sqlcommand ("select Machine_Code,Machine_Name,Status from
Machine_Master where '" & combolinecode.Text & "' = Line_Code" )
I wanna change the value of Status from 1 => active and 0 => not active.
You can do this with the ANSI standard case statement in almost all databases:
select Machine_Code, Machine_Name,
(case when Status = 1 then 'active' else 'not active' end) as status
from Machine_Master
where '" & combolinecode.Text & "' = Line_Code";
I fear that if you are using VBA you might be using Access, which has its own way:
select Machine_Code, Machine_Name,
iif(Status = 1, "active", "not active") as status
from Machine_Master
where '" & combolinecode.Text & "' = Line_Code";
You can use case :
select Machine_Code
, Machine_Name
, (case when Status = 1 then 'active' else 'not active' end) as Status
from Machine_Master
where '" & combolinecode.Text & "' = Line_Code

How to write the equivalent Sqlite statement for query given below? [duplicate]

This question already has answers here:
How to write the equivalent SQL case statement for query given below?
(2 answers)
Closed 8 years ago.
This is my working non-sql query:
Query = "select Cust_Id,Card_Number,Clients_Title,Address_Current,Phone_Number,Mobile_Number from Customer_New Where 1=1";
try
{
if (txt_title.Text != "")
Query += " and Clients_Title Like '%" + txt_title.Text + "%'";
if (txt_address.Text != "")
Query += " and Address_Current Like '%" + txt_address.Text + "%'";
if (txt_phone.Text != "")
Query += " and Phone_Number Like '%" + txt_phone.Text + "%'";
if (txt_mobile.Text != "")
Query += " and Mobile_Number Like '%" + txt_mobile.Text + "%'";
if (cbo_location.Text != "")
Query += " and AreaLocation Like '%" + cbo_location.Text + "%'";
}
catch { }
In this code the working of "where" clause is:
If all text boxes are null it selects all the records mean skip where
clause
if some text is entered in any 1 text box then section in 'where'
clause is made on that particular text box
if some text is entered in any multiple text box then section in
'where' clause is made according to them by fulfilling "AND"
condition between them .It mean all values entered into text boxes
must match with corresponding rows attributes
Here I am attempting to write its equivalent SQL statement .
SELECT Cust_Id, Clients_Title, Card_Number, Key_Person, Address_Current, Phone_Number, Mobile_Number, AreaLocation
FROM Customer_New
WHERE (#Clients_Title IS NULL OR Clients_Title = #Clients_Title )
AND (#Address_Current IS NULL OR Address_Current = #Address_Current )
AND (#Phone_Number IS NULL OR Phone_Number = #Phone_Number)
AND (#Mobile_Number IS NULL OR Mobile_Number = #Mobile_Number )
AND (#AreaLocation IS NULL OR AreaLocation = #AreaLocation)
Problem in this query is :
It search NULL or ''(empty string) from db tablt if nothing is provided in text box.I want as in above code if nothing entered in text box that attribute get skip from where clause and only values provided in text box are considered for checking in where clause.Can sql case and if else condition help in this scenario? Can anyone tell me how I can accomplish this ? Thanks
Note : In sqlite stored procedure don't exit .So guide me to write the correct sql query according to scenario.
Use the conditions
(#Clients_Title = ''
OR ((#Clients_Title != '') AND (Clients_Title = #Clients_Title)
and so on.
Here's the full version
SELECT Cust_Id, Clients_Title, Card_Number, Key_Person, Address_Current,
Phone_Number, Mobile_Number, AreaLocation FROM Customer_New
WHERE (#Clients_Title = ''
OR (#Clients_Title != '' AND Clients_Title LIKE '%'+#Clients_Title+'%'))
AND (#Address_Current = ''
OR (#Address_Current != '' AND Address_Current LIKE '%'+#Address_Current+'%'))
AND (#Phone_Number = ''
OR (#Phone_Number != '' AND Phone_Number LIKE '%'+#Phone_Number+'%'))
AND (#Mobile_Number = ''
OR (#Mobile_Number != '' AND Mobile_Number LIKE '%'+#Mobile_Number+'%'))
AND (#AreaLocation = ''
OR (#AreaLocation != '' AND AreaLocation LIKE '%'+#AreaLocation+'%'))
See comment below for supplying '' instead of NULL arguments. Otherwise the conditions get way too ugly, e.g.:
AND (#AreaLocation = '' OR #AreaLocation IS NULL
OR ((#AreaLocation != '' AND #AreaLocation IS NOT NULL)
AND AreaLocation LIKE '%'+#AreaLocation+'%'))
You probably need to test if the parameter is an empty string so you can do
AND (#param IS NULL OR #param = '' OR #param = param)
At-last i made the query that fulfill my requirements
SELECT Cust_Id, Clients_Title, Card_Number, Key_Person, Address_Current, Phone_Number, Mobile_Number, AreaLocation
FROM Customer_New
where (CASE
WHEN #Clients_Title != '' THEN Clients_Title=#Clients_Title
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #Address_Current != '' THEN Address_Current =#Address_Current
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #Phone_Number != '' THEN Phone_Number=#Phone_Number
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #Mobile_Number != '' THEN Mobile_Number=#Mobile_Number
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #AreaLocation != '' THEN AreaLocation =#AreaLocation
ELSE
NULL IS NULL
END)

How to write the equivalent SQL case statement for query given below?

This is my working query:
Query = "select Cust_Id,Card_Number,Clients_Title,Address_Current,Phone_Number,Mobile_Number from Customer_New Where 1=1";
try
{
if (txt_title.Text != "")
Query += " and Clients_Title Like '%" + txt_title.Text + "%'";
if (txt_address.Text != "")
Query += " and Address_Current Like '%" + txt_address.Text + "%'";
if (txt_phone.Text != "")
Query += " and Phone_Number Like '%" + txt_phone.Text + "%'";
if (txt_mobile.Text != "")
Query += " and Mobile_Number Like '%" + txt_mobile.Text + "%'";
if (cbo_location.Text != "")
Query += " and AreaLocation Like '%" + cbo_location.Text + "%'";
}
catch { }
Here I am attempting to write its equivalent SQL case statement .
SELECT Cust_Id, Clients_Title, Card_Number, Key_Person, Address_Current, Phone_Number, Mobile_Number, AreaLocation
FROM Customer_New
WHERE 1 = CASE WHEN #Clients_Title != " " THEN Clients_Title AND
WHEN #Address_Current != " " THEN Address_Current AND
WHEN #Phone_Number != " " THEN Phone_Number AND
WHEN #Mobile_Number != " " THEN Mobile_Number AND
WHEN #AreaLocation != " " THEN AreaLocation
END
Can any one correct my case statement?
I think you just want this - no CASE required:
SELECT Cust_Id, Clients_Title, Card_Number, Key_Person, Address_Current, Phone_Number, Mobile_Number, AreaLocation
FROM Customer_New
WHERE
(#Clients_Title = '' OR Clients_Title LIKE '%'+#Clients_Title+'%') AND
(#Address_Current = '' OR Address_Current LIKE '%'+#Address_Current+'%') AND
(#Phone_Number = '' OR Phone_Number LIKE '%'+#Phone_Number+'%') AND
(#Mobile_Number = '' OR Mobile_Number LIKE '%'+#Mobile_Number+'%') AND
(#AreaLocation = '' OR AreaLocation LIKE '%'+#AreaLocation+'%')
Because that at least closely resembles your non-SQL code.
SELECT Cust_Id, Clients_Title, Card_Number, Key_Person, Address_Current, Phone_Number, Mobile_Number, AreaLocation
FROM Customer_New
where (CASE
WHEN #Clients_Title != '' THEN Clients_Title=#Clients_Title
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #Address_Current != '' THEN Address_Current =#Address_Current
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #Phone_Number != '' THEN Phone_Number=#Phone_Number
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #Mobile_Number != '' THEN Mobile_Number=#Mobile_Number
ELSE
NULL IS NULL
END)
AND(CASE
WHEN #AreaLocation != '' THEN AreaLocation =#AreaLocation
ELSE
NULL IS NULL
END)

Initiate Rollback if any SQL command fails

I'm looking at updating an old PowerShell script I ran for inserting Exchange Message Tracking logs into SQL. Due to the way I am pulling the Message Tracking logs into a tab delimited CSV file and then importing them, I have quite a big SQL statement that I'd like to Rollback and throw an exception in case of errors or problems...
I am doing this in the following order:
Truncating a Temp Table I'd created earlier in the script.
Bulk inserting the Logs from the CSV file into the Temp Table.
Inserting the Message Tracking rows into a Message Tracking table
from the Temp Table
Inserting the Recipient info into a Recipients table from the Temp
Table.
Updating my Servers table to reflect the fact that I've successfully
stepped forwards in time and inserted the logs.
Below is my function from PowerShell, should be easy to see what is running even if you don't know PowerShell:
Function Import-TrackingLogs
{
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandTimeOut = 2000
$Command.CommandText = "
TRUNCATE TABLE $TempTable1;
BULK INSERT $TempTable1
FROM '$ExportTrackingFile'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = '\t'
);
INSERT INTO E12_MessageTracking
SELECT
CASE LEN([TimeStamp]) WHEN 2 THEN NULL ELSE REPLACE([TimeStamp], '" + [char]34 + "', '') END AS [TimeStamp],
CASE LEN([Sender]) WHEN 2 THEN NULL ELSE REPLACE([Sender], '" + [char]34 + "', '') END AS [Sender],
CASE LEN([Recipients]) WHEN 2 THEN NULL ELSE REPLACE([Recipients], '" + [char]34 + "', '') END AS [Recipients],
CASE LEN([MessageSubject]) WHEN 2 THEN NULL ELSE REPLACE([MessageSubject], '" + [char]34 + "', '') END AS [MessageSubject],
CASE LEN([EventId]) WHEN 2 THEN NULL ELSE REPLACE([EventId], '" + [char]34 + "', '') END AS [EventId],
CASE LEN([Source]) WHEN 2 THEN NULL ELSE REPLACE([Source], '" + [char]34 + "', '') END AS [Source],
CASE LEN([MessageId]) WHEN 2 THEN NULL ELSE REPLACE([MessageId], '" + [char]34 + "', '') END AS [MessageId],
CASE LEN([InternalMessageId]) WHEN 2 THEN NULL ELSE REPLACE([InternalMessageId], '" + [char]34 + "', '') END AS [InternalMessageId],
CASE LEN([RecordGuid]) WHEN 2 THEN NULL ELSE REPLACE([RecordGuid], '" + [char]34 + "', '') END AS [RecordGuid],
CASE LEN([ClientIp]) WHEN 2 THEN NULL ELSE REPLACE([ClientIp], '" + [char]34 + "', '') END AS [ClientIp],
CASE LEN([ServerHostname]) WHEN 2 THEN NULL ELSE REPLACE([ServerHostname], '" + [char]34 + "', '') END AS [ServerHostname],
CASE LEN([ConnectorId]) WHEN 2 THEN NULL ELSE REPLACE([ConnectorId], '" + [char]34 + "', '') END AS [ConnectorId],
CASE LEN([RecipientStatus]) WHEN 2 THEN NULL ELSE REPLACE([RecipientStatus], '" + [char]34 + "', '') END AS [RecipientStatus],
CASE LEN([RecipientCount]) WHEN 2 THEN NULL ELSE REPLACE([RecipientCount], '" + [char]34 + "', '') END AS [RecipientCount],
CASE LEN([TotalBytes]) WHEN 2 THEN NULL ELSE REPLACE([TotalBytes], '" + [char]34 + "', '') END AS [TotalBytes],
CASE LEN([FromServer]) WHEN 2 THEN NULL ELSE REPLACE([FromServer], '" + [char]34 + "', '') END AS [FromServer]
FROM $TempTable1;
INSERT INTO E12_MessageTracking_Recipients
SELECT
SUBSTRING (s.[TimeStamp], 2, LEN(s.[TimeStamp]) -2) AS [TimeStamp],
CASE LEN(s.[MessageId]) WHEN 2 THEN NULL ELSE (SUBSTRING (s.[MessageId], 2, LEN(s.[MessageId]) -2)) END AS [MessageId],
CASE LEN(s.[InternalMessageId]) WHEN 2 THEN NULL ELSE (SUBSTRING (s.[InternalMessageId], 2, LEN(s.[InternalMessageId]) -2)) END AS [InternalMessageId],
CASE LEN(s.[RecordGuid]) WHEN 2 THEN NULL ELSE (SUBSTRING (s.[RecordGuid], 2, LEN(s.[RecordGuid]) -2)) END AS [RecordGuid],
f.Value AS [Recipient]
FROM #E12_MessageTracking AS s
CROSS APPLY dbo.SplitStrings(SUBSTRING(s.[Recipients], 2, LEN(s.[Recipients]) -2), '|') AS f;
UPDATE E12_MessageTracking_Servers
SET LogUpdatedTime = '$EndTime';"
$Command.ExecuteNonQuery() | Out-Null
}
I could wrap each individual command into a Powershell try/catch block, but figured it might be better to see if SQL can handle this for me.
This was my previous rollback in PowerShell:
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandTimeOut = 30
$Command.CommandText = "
DELETE FROM E12_MessageTracking WHERE TimeStamp >= '$StartTime';
DELETE FROM E12_MessageTracking_Recipients WHERE TimeStamp >= '$StartTime';
UPDATE E12_MessageTracking_Servers
SET LogUpdatedTime = '$StartTime';"
$Command.ExecuteNonQuery() | Out-Null
I was looking at this page SQL Server - transactions roll back on error?, but unsure how I would wrap that into my commands as I'm not just running one thing, but multiple commands.
Thanks!
Consider using xact_abort:
set xact_abort on
begin transaction
<your big sql statement here>
commit transaction

Can these two SQL statements be made into one? Changing multiple indices with two constraints

I have a form that users can use to edit data in my database. The database is structured like this:
If a user wants to edit both a FAVE_COLOR and a FAVE_FOOD, how would I go about doing that in my SQL statement? I can think of this, but is there a way to do this in one statement?
string sql1 = "UPDATE MYTABLE " +
"SET PROP_VALUE = '" + form["color"] + "' " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME = 'FAVE_COLOR'"
string sql2 = "UPDATE MYTABLE " +
"SET PROP_VALUE = '" + form["food"] + "' " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME = 'FAVE_FOOD'"
string sql = "UPDATE MYTABLE " +
"SET PROP_VALUE = CASE " +
"WHEN PROP_NAME = 'FAVE_COLOR' THEN '" + form["color"] + "' " +
"WHEN PROP_NAME = 'FAVE_FOOD' THEN '" + form["food"] + "' " +
"END " +
"WHERE ID = " + form["id"] + " " +
"AND PROP_NAME IN ('FAVE_COLOR', 'FAVE_FOOD')"
But beware of SQL injection! You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
You can use case statements:
UPDATE MYTABLE
SET PROP_VALUE = (
CASE favefood
WHEN PROP_NAME = 'FAVE_FOOD'
THEN 'PIZZA'
CASE favecolor
WHEN PROP_NAME = 'FAVE_COLOR'
THEN 'BLUE'
WHERE ID = #myIdValue
For MS SQL Server you can use an UPDATE FROM which will update two properties at the same time, like this:
CREATE TABLE MYTABLE (
ID INT,
PROP_NAME VARCHAR(20),
PROP_VALUE VARCHAR(20));
go
INSERT INTO MYTABLE VALUES (1, 'A','B')
go
INSERT INTO MYTABLE VALUES (1, 'C', 'D')
go
UPDATE MYTABLE
SET PROP_VALUE = X.PROP_VALUE
FROM MYTABLE MT JOIN (
SELECT 'A' AS PROP_NAME, 'F' AS PROP_VALUE
UNION
SELECT 'C' AS PROP_NAME, 'G' AS PROP_VALUE) AS X ON MT.PROP_NAME = X.PROP_NAME
WHERE ID = 1
For other SQL DB server the solution should be similar if not identical.