vb.net select statement with parameters - sql

Hi all I am having a weird problem on a aspx page.
I have a select statement where the where clause has 2 options
The result of the query should populate a datagrid
SELECT TOP 10
[Last Name], [First Name], SSN,
[Box Label], [Original Box Number],
[Student ID], FolderName, DOB, [Transcript On File Y/N],
UserID, [School ID],
[Box Number], [School Name], Comment, SW, Code, Descrip
FROM
Main
WHERE
([Last Name] = ?) OR ([First Name] = ?)
When I put just one of the parameters (ie: lastname) nothing gets populated to the datagrid, but if I put data in both parameter is fills the datagrid with data.
I tested the select statement to verify that it does get data when I choose one or the other, but when I run it online it requires both fields to have data.
very weird...

Related

Selecting additional data/values to display as column in query or in form

I have an employee index, that I need to run queries on for each employee, and display that output along with the original employee.
So say the employee index has an ID, batch, status, and multiple other columns. I have a table where I keep track of every time a column in the employee index changes. I want to display and later export dates of when certain columns use to equal other values, right along side the original employee row.
Naturally I tried creating a form to display multiple value, added a text box to hold my extra information, and changed the value of the text box for each Form_Current event in VBA.
Private Sub Form_Current()
Me.txtPhaseOne = SimpleLookup("SELECT TOP 1 ChangeDate FROM EmployeeVariables WHERE VariableName = ""Batch"" AND EmployeeID = " & Me.Recordset("ID Number") & " ORDER BY ChangeDate ASC", "ChangeDate")
End Sub
It seemed to work at first...
Until I realized the dates were set to whatever the current record date should be
[
So then I tried a join:
SELECT
EmployeeIndex.[ID Number],
EmployeeIndex.Batch,
EmployeeIndex.Status,
EmployeeIndex.[First name],
EmployeeIndex.[Last name],
EVA.ChangeDate as Phase1
FROM
EmployeeIndex
(SELECT TOP 1 ChangeDate FROM EmployeeVariables WHERE EmployeeID = EmployeeIndex.[ID Number] ORDER BY CHangeDate) EVA
Which would work, if I could some how prefetch EmployeeIndex.[ID Number]. (I didn't name these columns) Except I haven't got the slightest clue and I'm running on fumes.
SELECT
EmployeeIndex.[ID Number],
EmployeeIndex.Batch,
EmployeeIndex.Status,
EmployeeIndex.[First name],
EmployeeIndex.[Last name],
EVA.ChangeDate as Phase1
FROM
EmployeeIndex
INNER JOIN
(SELECT TOP 1 EmployeeID, ChangeDate FROM EmployeeVariables WHERE ORDER BY ChangeDate) EVA
ON EmployeeIndex.[ID Number] = EVA.EmployeeID
Try with a subquery:
SELECT
EmployeeIndex.[ID Number],
EmployeeIndex.Batch,
EmployeeIndex.Status,
EmployeeIndex.[First name],
EmployeeIndex.[Last name],
(SELECT Max(EVA.ChangeDate)
FROM EmployeeVariables AS EVA
WHERE EVA.EmployeeID = EmployeeIndex.[ID Number]) AS Phase1
FROM
EmployeeIndex
Cross Apply will be perfect for your TOP 1 case, as it will run for each employeeID rather than just joining on 1

LOOP and COUNT in a SELECT statement SQL SERVER

I have a view with these columns
and i want to extract this data
i am doing it in SQL Server manually in several steps and i want to automate it so that i can run a select statement directly from a macro and save it in excel file.
Here is what i am doing
select distinct
CASE
WHEN Userid ='jsolar' THEN 'Jack Solar'
WHEN Userid ='jkrcmarikova' THEN 'Jana Krcmarikova'
WHEN Userid ='lfialova' THEN 'lucia fialova'
WHEN Userid ='zsnopkova' THEN 'zuzana snopkova'
END AS [User Name]
, Region
from [SC].[vw_X86_Orders_By_UserID_GAMMA]
order by Region, [User Name]
Then i copy the result in excel file and run other queries for each user
SELECT Count ( DISTINCT [Order Number])
FROM [SC].[vw_X86_Orders_By_UserID_GAMMA]
where Userid LIKE 'jsolar'
AND Region LIKE 'CENTRAL'
and [Order Entry Date] = '2016-10-27'
i save this result in number of distinct order number. Then i run this query
SELECT Count ( DISTINCT CONCAT ([Order Number], [Line No]))
FROM [SC].[vw_X86_Orders_By_UserID_GAMMA]
where Userid LIKE 'jsolar'
AND Region LIKE 'CENTRAL'
and [Order Entry Date] = '2016-10-27'
I save this result in number of distinct order number concatenated with line no. And i repeat the same for each user
At the end it should be something like this in Excel
Is there a way how to do this in one select statement to loop each user and count for all users at the same time ? Thank you very much.
I really don't think you need a "LOOP". SQL operates best in set based operations returning recordsets with many rows. So we need to treat [SC].[vw_X86_Orders_By_UserID_GAMMA] as an entire set and simply update the case statement to translate all users names (assuming you have to have them, or you could do a vlookup on the userID in excel after the fact)
I think what you're really after is the count(distinct column) in combination with a group by on userID and region.
Based on comments I think you would need to amend the case statements in the select and group by to contain the translation for all the users.
I think there's too many unknowns to provide a 100% correct response but here's a shot across the bow..
SELECT CASE WHEN Userid ='jsolar' THEN 'Jack Solar'
WHEN Userid ='jkrcmarikova' THEN 'Jana Krcmarikova'
WHEN Userid ='******' THEN '**** *******'
WHEN Userid ='****' THEN '***** ****' END AS [User Name]
, Region
, count(distinct [Order Number]) as cntDistinctOrders
, count(Distinct concat([order Number], [Line No]) as cntDistinctOrderLines
FROM [SC].[vw_X86_Orders_By_UserID_GAMMA]
WHERE [Order Entry Date] = '2016-10-27'
-- and Region = 'CENTRAL' don't think you need this the group by handles same names in different regions keeping them distinct and counts seperate.
GROUP BY CASE WHEN Userid ='jsolar' THEN 'Jack Solar'
WHEN Userid ='jkrcmarikova' THEN 'Jana Krcmarikova'
WHEN Userid ='******' THEN '**** *******'
WHEN Userid ='****' THEN '***** ****'
END
, Region
ORDER BY [User Name], Region
To put this in plain English...
You want all the usernames and regions for each user in the [SC].[vw_X86_Orders_By_UserID_GAMMA] schema.table showing the distinct count of orders and order lines for a specific date.
If you can use a Vlookup in excel for the names you could getaway without the case statements and all that extra code..
SELECT UserId [User Name]
, Region
, count(distinct [Order Number]) as cntDistinctOrders
, count(Distinct concat([order Number], [Line No]) as cntDistinctOrderLines
FROM [SC].[vw_X86_Orders_By_UserID_GAMMA]
WHERE [Order Entry Date] = '2016-10-27'
-- and Region = 'CENTRAL' don't think you need this the group by handles same names in different regions keeping them distinct and counts seperate.
GROUP BY CASE UserID
, Region
ORDER BY [User Name], Region
--note because the group by executes before the select statement, we have to group by the USERID and not the alias name of [User name]

Putting two SQL statements together

I am new at SQL and I am just trying to add two SQL statements together which are below. The first table is a basic make table pulling in only fields I need and then the second table is pulling the same information but appending it to the first table I made in Step 1 . I have been doing some research and what I think I need to do is a union query but I am not sure how to go about that any help please?
/*first step*/
/*Select
[NPI],
[Last Name],
[First Name],
[Middle Name],
Suffix,
Gender,
[Spoken Languages]
Into [Provider Table]
From sylvia.dbo.UNIQUEACN*/
/*Second step appending PCCN Providers*/
Insert into [sylvia].dbo.[provider Table] ( NPI, [Last Name], [First Name], [Middle Name], Suffix, Gender, [spoken languages] )
Select sylvia.dbo.[PCCNProviders].NPI, sylvia.dbo.PCCNProviders.[Last Name],sylvia.dbo.PCCNProviders.[First Name], sylvia.dbo.PCCNProviders.[Middle Name], sylvia.dbo.PCCNProviders.suffix, sylvia.dbo.PCCNProviders.gender, sylvia.dbo.PCCNProviders.[Spoken Languages]
From sylvia.dbo.[PCCNproviders];
Because your 2 tables have the same number and order of columns, you can simply execute the below query. Use UNION ALL if you want to keep duplicated values from both tables or just UNION if you want all duplicated values to be removed.
SELECT *
-- INTO [Combined_table]
FROM sylvia.dbo.UNIQUEACN
UNION ALL
SELECT *
FROM sylvia.dbo.[PCCNproviders]
Thank you I did just that I did a union query and its way cleaner then what I was doing .. Thanks again!! Ive been doing SQL for a week and as you can tell its a struggle but getting there
Select
a.[NPI],
a.[Last Name],
a.[First Name],
a.[Middle Name],
a.Suffix,
a.Gender,
a.[Spoken Languages]
Into [Provider test]
From sylvia.dbo.UNIQUEACN a
Union
Select
b.[NPI],
b.[Last Name],
b.[First Name],
b.[Middle Name],
b.Suffix,
b.Gender,
b.[Spoken Languages]
From sylvia.dbo.[PCCNproviders] b

SQL multiple rows with same row names to column

I have the following data in SQL (nvarchar, nvarchar)
Name: Test Person
Phone Number: 290831283
Fax Number: 192389182
Email Address: test#test.com
Name: Abacus Testing
Phone Number: 901823908
Fax Number: 9213989182
Email Address: abacus#test.com
How can I format this data to be:
[Name] [Phone Number] [Fax Number] [Email Address]
Test Person 290831283 192389182 test#test.com
Abacus Testing 901823908 9213989182 abacus#test.com
So basically setting the rows into matching column
I was hoping to use a Pivot table, but I only get the first row due to aggregation.
SELECT [Name], [Phone Number], [Fax Number], [Email Address]
FROM
(
SELECT
ColumnName,
Data
FROM
TheData
) SRC
PIVOT
(
MAX(Data)
FOR ColumnName IN ([Name], [Phone Number], [Fax Number], [Email Address])
) PIV
I would prefer no CURSOR methods, any alternatives?
Edit: added other fields available for use
The other fields available are Label Id for each entry. i.e Name=1, PhoneNumber=2, FaxNumber=3, EmailAddress=4
The common Id for each of the 4 entries is also available. i.e first 4 entries have id 1001, second 4 entries have id 1002
Following clarification in the comments you just need to add CommonId in to your source.
This is not an aggregated or spreading column so it will be used as a grouping column and you will get a row per distinct value of that.
SELECT [Name], [Phone Number], [Fax Number], [Email Address]
FROM
(
SELECT
CommonId,
ColumnName,
Data
FROM
TheData
) SRC
PIVOT
(
MAX(Data)
FOR ColumnName IN ([Name], [Phone Number], [Fax Number], [Email Address])
) PIV

Entire Union query returns no results if part of it returns no results

I've created the folllowing Union query, which works fine most of the time:
SELECT [%$###_Alias].[Contact ID], [%$###_Alias].[Mailing Name]
FROM (SELECT [Referrals - Contacts Within Organisations].[Contact ID], [Referrals - Contacts Within Organisations].[Mailing Name], [Referrals - Contacts Within Organisations].[Surname], [Referrals - Contacts Within Organisations].[First name]
FROM [Referrals - Contacts Within Organisations]
UNION SELECT "0" as [Contact ID], "View all contacts" as [Mailing Name], "0" as [Surname], "0" as [First name]
FROM [Referrals - Contacts Within Organisations]) AS [%$###_Alias]
ORDER BY [%$###_Alias].Surname, [%$###_Alias].[First name];
This adds an initial row of "View all contacts" at the top of whatever the query returns.
However, if the "actual" query part of it returns no results, the entire query returns no results, whereas I'd always want the initial row to appear regardless.
Is this possible, and if so, what am I doing wrong? Thanks.
EDIT: Thanks all for your help. The final working query is below for reference of anyone else who needs this sort of thing:
SELECT A.[Contact ID], A.[Mailing Name]
FROM (SELECT "0" as [Contact ID], "View all contacts" as [Mailing Name], "0" as [Surname], "0" as [First name]
FROM [Dummy]
UNION
SELECT [Referrals - Contacts Within Organisations].[Contact ID], [Referrals - Contacts Within Organisations].[Mailing Name], [Referrals - Contacts Within Organisations].[Surname], [Referrals - Contacts Within Organisations].[First name]
FROM [Referrals - Contacts Within Organisations]) AS A
ORDER BY A.Surname, A.[First name];
To return always one row with data in SQL, even when you are manually providing the values, you need to be selecting from a table that has at least one row, I suggest using a tblDummy with one field of random information.
e.g:
SELECT "Hello", "Goodbye"
FROM tblDummy
As a side note I would also try and get rid of:
[%$###_Alias]
This can be accomplished by aliasing your Derived tables by adding:
(SELECT * FROM Blah) AS A
for example to name the derived table as A