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

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

Related

Issue with expected parameters in SQL statement

I am trying to run a small append query in VBA to add new data for a duplicated record.
strsql = " INSERT INTO tblQuoteNumGeneration ( JobID, BaseQuote, Yearnum, RevisionNum )"
strsql = strsql & " SELECT JobID = [Forms]![JobQuote]![JobID], BaseQuote = " & _
QuoteNumber & ", YearNum = " & MyYear & ", RevisionNum = " & NewRev & ""
strsql = strsql & " FROM tblQuoteNumGeneration"
However, I am getting an Expected parameters error. On a debug.print, it outputs:
INSERT INTO tblQuoteNumGeneration ( JobID, BaseQuote, Yearnum, RevisionNum )
SELECT JobID = [Forms]![JobQuote]![JobID], BaseQuote = 14937, YearNum = 20, RevisionNum = 2
FROM tblQuoteNumGeneration
Could someone who is a bit more versed in SQL help point me to my mistake?
You have incorrect SQL statement generated. Instead of:
INSERT INTO tblQuoteNumGeneration ( JobID, BaseQuote, Yearnum, RevisionNum )
SELECT JobID = [Forms]![JobQuote]![JobID], BaseQuote = 14937, YearNum = 20, RevisionNum = 2
FROM tblQuoteNumGeneration
you should have:
INSERT INTO tblQuoteNumGeneration ( JobID, BaseQuote, Yearnum, RevisionNum )
SELECT JobID, BaseQuote, Yearnum, RevisionNum
FROM tblQuoteNumGeneration

Limit return data for 7 days

I have this table which I use to store events
CREATE TABLE EVENT(
ID INTEGER NOT NULL,
SOURCE VARCHAR2(50 ),
TYPE VARCHAR2(50 ),
EVENT_DATE DATE,
DESCRIPTION VARCHAR2(100 )
)
/
I use this query to get the results for all types of events
dbRequest.setPreparedStatement("SELECT "
+ " COUNT(*) \"ALL\","
+ " COUNT(CASE WHEN TYPE = 'Critical' THEN 1 END) \"CRITICAL\", "
+ " COUNT(CASE WHEN TYPE = 'Info' THEN 1 END) \"INFO\", "
+ " COUNT(CASE WHEN TYPE = 'Warning' THEN 1 END) \"WARN\", "
+ " COUNT(CASE WHEN TYPE = 'Error' THEN 1 END) \"ERROR\" "
+ " FROM "
+ " EVENT");
How I can modify the query to get the rows only for last 7 days?
Also for some reason the query is not working with low capital data.
dbRequest.setPreparedStatement("SELECT "
+ " COUNT(*) \"ALL\","
+ " COUNT(CASE WHEN TYPE = 'Critical' THEN 1 END) \"CRITICAL\", "
+ " COUNT(CASE WHEN TYPE = 'Info' THEN 1 END) \"INFO\", "
+ " COUNT(CASE WHEN TYPE = 'Warning' THEN 1 END) \"WARN\", "
+ " COUNT(CASE WHEN TYPE = 'Error' THEN 1 END) \"ERROR\" "
+ " FROM "
+ " EVENT"
+ " WHERE EVENT_DATE >= TRUNC(SYSDATE)-7");

How to write an sqlite query for the following scenario? [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.
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)

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.