Stored Procedures and asp.net programmability; variable or SQL - asp.net

Trying to display a users Lastname, Firstname --- Website
And I need to insert a comma and space after Lastname to a GridView.
I am trying to add a CASE statement in SQL and having trouble figuring it out.
Perhaps I need to use #parameter (scalar variable?) to abstract the
memory read from CASE statement; or my syntax is wrong and I just don't
understand.
SELECT
CASE
WHEN IsNull(people_Table.firstName, '') = ''
THEN CONCAT(people_Table.lastName, ', ', people_Table.firstName)
ELSE people_Table.lastName
END as fullName,
people_Table.website
FROM
people_Table
INNER JOIN
membership_Table on people_Table.ID = membership_Table.personID
WHERE
rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY
people_Table.lastName
Getting SQL Server error:
Msg 208, Level 16, State 1, Line 1
Invalid object name 'people_Table'.
Otherwise I suppose I should use an asp databoundevent in the template.
What is better for performance and security?

SELECT ISNULL(people_Table.lastName + ', ', '')
+ ISNULL(people_Table.firstName , '') as fullName
, people_Table.website
FROM people_Table INNER JOIN membership_Table on people_Table.ID =
membership_Table.personID
WHERE rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY people_Table.lastName
OR
SELECT COALESCE(people_Table.lastName + ', ', '')
+ COALESCE(people_Table.firstName , '') as fullName
, people_Table.website
FROM people_Table INNER JOIN membership_Table on people_Table.ID =
membership_Table.personID
WHERE rectype = 'Master'
AND membershipType = 'Business'
AND expirationDate > GetDate()
ORDER BY people_Table.lastName

Related

Filler word for SQLite statement to return any and all rows using WHERE [duplicate]

I am doing my crm project with SQLITE+FLASK. And I need a feature is let user to input the condition to filer the result.
I hope that my SQL statement can ignore the WHERE condition if the parameter is space or null.
For example, My input is "NAME", "AGE", "GENDER"
so my statement will be
SELECT *
FROM CUSTOMER
WHERE NAME = 'James' AND AGE = '25' AND GENDER = 'M'
But I hope that if user did not enter "NAME" my SQL statement can be something like the code below
SELECT *
FROM CUSTOMER
WHERE AGE = '25' AND GENDER = 'M'
I know maybe I can do this with string concat, but I hope I can do this by SQL statement.
You can do it with the OR operator for each of the columns, by checking also if the parameter value that you pass is NULL or a string with spaces:
SELECT *
FROM CUSTOMER
WHERE (NAME = :name OR TRIM(COALESCE(:name, '')) = '')
AND (AGE = :age OR TRIM(COALESCE(:age, '')) = '')
AND (GENDER = :gender OR TRIM(COALESCE(:gender, '')) = '')
You can use null condition as follows:
SELECT *
FROM CUSTOMER
WHERE (NAME = :name_input or :name_input is null)
AND (AGE = :age_input or :age_input is null)
AND (GENDER = :gender_input or :gender_input is null)

Error on INSERT INTO SELECT in query hosted on variable

I'm a little bit conffused.
Can anyone tell me why i get sintaxis error on the next script?
declare #schema1 NVARCHAR(100)
set #schema1 = 'ex.:DATABASENAME'
declare #query NVARCHAR(500)
set #query = 'INSERT UsersSessions (UserSessionId, IpAddress, ChannelId, IsEmployee, UserId, ClientFullName, UserAgent, StartDate, ExpirationDate, SessionDuration)
SELECT us.UserSessionId, us.IpAddress, us.ChannelId, CASE WHEN us.ChannelId = 2 THEN 1 ELSE 0 END AS IsEmployee, us.UserId, (u.Name + u.LastName) as ClientFullName, us.UserAgent, us.StartDate, us.ExpirationDate, (us.ExpirationDate-us.StartDate) AS SessionDuration
FROM ' + #schema1 + '.UsersSessions us INNER JOIN ' + #schema1 + '.Users u ON us.UserId = u.UserId WHERE us.UserSessionId NOT IN (SELECT UserSessionId FROM UsersSessions)'
EXEC(#query)
RESULT:
Msg 156, Level 15, State 1, Line 15
Incorrect syntax near the keyword 'Use'.
Completion time: 2021-11-16T11:10:32.6309920-03:00
If i remove the Insert block, i get the script running
declare #schema1 NVARCHAR(100)
set #schema1 = 'ex.:DATABASENAME'
declare #query NVARCHAR(500)
set #query = '
SELECT us.UserSessionId, us.IpAddress, us.ChannelId, CASE WHEN us.ChannelId = 2 THEN 1 ELSE 0 END AS IsEmployee, us.UserId, (u.Name + u.LastName) as ClientFullName, us.UserAgent, us.StartDate, us.ExpirationDate, (us.ExpirationDate-us.StartDate) AS SessionDuration
FROM ' + #schema1 + '.UsersSessions us INNER JOIN ' + #schema1 + '.Users u ON us.UserId = u.UserId WHERE us.UserSessionId NOT IN (SELECT UserSessionId FROM UsersSessions)'
EXEC(#query)
RESULT:
(1 row affected)
Completion time: 2021-11-16T11:11:07.6741062-03:00
I think some char is missing?
Thanks and regards!
Your query variable length is not sufficient, modify it as below. Also, schema name can accept only certain characters, colon is not allowed I guess.
declare #query NVARCHAR(max)

FakeFunction Results based on Test

I'm using tSqlt to unit test a stored procedure. This stored proc joins to a table-valued function, the function takes no parameters and the results are filtered via the join on clause.
I'm writing multiple tests for the stored proc. Is there a way to to fake the function in such a way that I could return different results based on the test that is being run.
The only solution I can think of is to create a fake per test, which is possible but a little more than clunky.
I imagine an ideal solution would be some sort of variable exposed in tsqlt that would allow me to determine which test I'm in and use some sort of case statement or something.
I use following procedure for that. It is not ideal, but working:
CREATE PROCEDURE [tSQLt].[FakeFunction2]
#FunctionName VARCHAR(200)
, #SchemaName VARCHAR(200) = 'dbo'
, #tmpTableName VARCHAR(200)
AS
BEGIN
DECLARE #Params VARCHAR(2000);
DECLARE #NewName VARCHAR(MAX) = #FunctionName + REPLACE(CAST(NEWID() AS VARCHAR(100)), '-', '');
DECLARE #FunctionNameWithSchema VARCHAR(MAX) = #SchemaName + '.' + #FunctionName;
DECLARE #RenameCmd VARCHAR(MAX) = 'EXEC sp_rename ''' + #FunctionNameWithSchema + ''', ''' + #NewName + ''';';
DECLARE #newTbleName VARCHAR(200) = #SchemaName + '.tmp' + REPLACE(CAST(NEWID() AS VARCHAR(100)), '-', '');
DECLARE #newTblStmt VARCHAR(2000) = 'SELECT * INTO ' + #newTbleName + ' FROM ' + #tmpTableName;
EXEC tSQLt.SuppressOutput #command = #newTblStmt;
SELECT #Params = p.params
FROM
( SELECT DISTINCT ( SELECT p1.name + ' ' + type1.name + b.brk + ',' AS [text()]
FROM sys.types type1
JOIN sys.parameters p1 ON p1.system_type_id = type1.system_type_id
CROSS APPLY
( SELECT CASE WHEN type1.name LIKE '%char' OR type1.name = 'varbinary' THEN
REPLACE(
'(' + CAST(p1.max_length AS VARCHAR(5)) + ')', '-1', 'MAX')
WHEN type1.name IN ('decimal', 'numeric') THEN
'(' + CAST(p1.precision AS VARCHAR(5)) + ', '
+ CAST(p1.scale AS VARCHAR(5)) + ')'
WHEN type1.name IN ('datetime2') THEN
'(' + CAST(p1.scale AS VARCHAR(5)) + ')'
ELSE ''
END AS brk) b
WHERE p1.object_id = p.object_id
ORDER BY p1.parameter_id
FOR XML PATH('')) [parameters]
FROM sys.objects AS o
LEFT JOIN sys.parameters AS p ON p.object_id = o.object_id
LEFT JOIN sys.types AS t ON t.system_type_id = p.system_type_id
WHERE o.name = #FunctionName AND o.schema_id = SCHEMA_ID(#SchemaName)) [Main]
CROSS APPLY
(SELECT LEFT(Main.[parameters], LEN(Main.[parameters]) - 1) params) AS p;
EXEC tSQLt.SuppressOutput #command = #RenameCmd;
DECLARE #newFunctionStmt VARCHAR(MAX) = '';
SET #newFunctionStmt = 'CREATE FUNCTION [' + #SchemaName + '].[' + #FunctionName + '](' + COALESCE(#Params,'') + ')';
SET #newFunctionStmt = #newFunctionStmt + ' RETURNS TABLE AS RETURN (SELECT * FROM ' + #newTbleName + ');';
EXEC tSQLt.SuppressOutput #command = #newFunctionStmt;
END;
and usage:
INSERT INTO #table
(col1
, col2
, col3)
VALUES
('a', 'b', 'c'),
('d', 'e', 'f');
EXEC tSQLt.FakeFunction2 #FunctionName = 'function_name'
, #SchemaName = 'dbo'
, #tmpTableName = '#table';
now with any passed parameter to that function it will always return the values from #table temp table
I thought of one potential solution.
I create a table within the test class schema and populate it with the results I wish to be returned per test.
CREATE TABLE testcalass.fakefunction_Results
(
ID INT,
Value NUMERIC(12, 5)
)
GO
CREATE FUNCTION testcalass.fakefunction()
RETURNS #results TABLE
(
ID INT,
Value NUMERIC(12, 5)
)
BEGIN
INSERT INTO #results
SELECT ID, Value FROM testcalass.fakefunction_Results
END
GO
So basically, I can populate is functions results at the top of my tests during the assemble section.

use operation logic inside SQL Query?

I have a Query string inside Employees Page that read URL Parameter
to get Companies employees from DataBase if parameter is ALL the page should display ALL Employees but if CompID Equal Specific ID it will Get only Employees for this Company to do that i am using two queries but i am sure that i can use only one query to get the same result
my Query String Parameter is :
String CompID = HttpUtility.UrlDecode(Request.QueryString["CompID"]);
The SQL Query to display ALL Employee is :
Query1 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
" TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
"TbEmp.address, TbComp.compName From TbEmp" +
" INNER JOIN TbComp on TbComp.compID = TbEmp.compID ORDER BY TbComp.compID"
The SQL Query to Display Employees for specific companie is :
Query2 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
" TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
"TbEmp.address, TbComp.compName From TbEmp" +
" INNER JOIN TbComp on TbComp.compID = TbEmp.compID WHERE TbEmp.compID = #CompID ORDER BY TbComp.compID DESC"
Can someone help me to merge those two queries in one query ?
The is a simple or-and case. Assuming your #CompID is numeric and you can send a zero to indicate the 'All' search...
INNER JOIN TbComp on TbComp.compID = TbEmp.compID
WHERE (#CompID = 0) or (#CompID <> 0 and TbEmp.compID = #CompID)
ORDER BY TbComp.compID DESC"
Although I would not suggest using queries to write your logic in asp.net (use stored procedures with parameters instead).
You can do this :
Solution 1 :
string Query1 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
" TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
"TbEmp.address, TbComp.compName From TbEmp" +
" INNER JOIN TbComp on TbComp.compID = TbEmp.compID " ;
String CompID = HttpUtility.UrlDecode(Request.QueryString["CompID"]);
if( CompID<>"")
{
Query1 += " WHERE TbEmp.compID = " + CompID //Beware : Chance of injection
}
Query1 +=" ORDER BY TbComp.compID";
Solution 2 : Assuming #CompID will be passed null if it is not there.
Query2 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
" TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
"TbEmp.address, TbComp.compName From TbEmp" +
" INNER JOIN TbComp on TbComp.compID = TbEmp.compID WHERE
TbEmp.compID = Isnull(#CompID, TbEmp.compID) ORDER BY TbComp.compID DESC"

dynamic query showing 'Unclosed quotation mark after the character string '),

i have a stored procedure in which i am getting error 'Unclosed quotation mark after the character string ' having a hard time with the script. please help me to find out what is wrong in my code.
here is my code.
ALTER PROCEDURE [dbo].[usp_Transfer]
#orgid bigint,
#SearchString nvarchar (500) = null,
#LocationId bigint = 0,
#ownerid bigint,
#OrderList varchar(MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.\
SET NOCOUNT ON;
DECLARE #SQL varchar(MAX)
BEGIN
SET #SQL = 'SELECT ProductID = ii.ProductId,
InvItemId = convert(bigint,0),Name = p.Name,
PrimaryImageID = p.PrimaryImageID,ProductNumberLabel = p.ProductNumberLabel,ProductNumber = p.ProductNumber,
category = isnull(c.Name,''),
qty = ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00),
SalePrice= ISNULL(p.SalePrice, 0.00),
EnteredQuantity=(case when (ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00) > 1) then 1.00 else ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00) end)
,Discount=0,u.UnitName,
u.UnitID
FROM dbo.[Inven] ii
Left Join dbo.[Product] p on ii.ProductId = p.ProductId and p.activestatus=1
Left Join dbo.[category] c on p.DefaultCategoryId = c.CategoryId
Left Join dbo.[Unit] u on p.UnitId=u.UnitId and u.Activestatus=1
WHERE p.OrganizationID = #orgid
AND ii.InventoryID IN(1634)
AND ii.ActiveStatus = 1
AND p.ActiveStatus = 1
AND p.IsDisabled = 0
And p.CanSale = 1
AND ii.InventoryID IN (' + #OrderList + ')
group by ii.ProductId, p.Name, p.PrimaryImageID, p.ProductNumberLabel, p.ProductNumber, c.Name,p.SalePrice,u.unitname,u.UnitID
having ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0) > 0
Order by p.ProductNumber, p.Name, c.Name '
--EXEC(#SQL)
PRINT(#SQL)
END
END
Two things of note.
First, does #OrderList contain any quotes?
Second, this line:
...' WHERE p.OrganizationID = #orgid '
Should be:
....'WHERE p.OrganizationID = ' + #orgid + '...'
The easy way to test if either of these are the cause of the problem is to comment both out, run it and see if it works, if it does then comment them in one at a time to see which one gives you the error.
Finally, you could rewrite this query and avoid using a dynamic query at all. I guess looking at the query you have done it because of the IN (' + #OrderList + ') clause. These posts might help you rework that section:
Parameterize an SQL IN clause
SQL Server - In clause with a declared variable
Update your SP as below:
Note: there are so many errors if solve one like quotation mark, declare variable #orgid and then conversion error
Your initial error due to : category = isnull(c.Name,''), replace it with category = isnull(c.Name,'''')
alter PROCEDURE [dbo].[usp_Transfer]
#orgid bigint=1,
#SearchString nvarchar (500) = null,
#LocationId bigint = 0,
#ownerid bigint=1,
#OrderList varchar(MAX)='1'
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.\
SET NOCOUNT ON;
DECLARE #SQL varchar(MAX)
BEGIN
SET #SQL = 'SELECT ProductID = ii.ProductId,
InvItemId = convert(bigint,0),Name = p.Name,
PrimaryImageID = p.PrimaryImageID,ProductNumberLabel = p.ProductNumberLabel,ProductNumber = p.ProductNumber,
category = isnull(c.Name,''''),
qty = ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00),
SalePrice= ISNULL(p.SalePrice, 0.00),
EnteredQuantity=(case when (ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00) > 1) then 1.00 else ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0.00) end)
,Discount=0,u.UnitName,
u.UnitID
FROM dbo.[Inven] ii
Left Join dbo.[Product] p on ii.ProductId = p.ProductId and p.activestatus=1
Left Join dbo.[category] c on p.DefaultCategoryId = c.CategoryId
Left Join dbo.[Unit] u on p.UnitId=u.UnitId and u.Activestatus=1
WHERE p.OrganizationID = '+CAST(#orgid AS VARCHAR(10))+'
AND ii.InventoryID IN(1634)
AND ii.ActiveStatus = 1
AND p.ActiveStatus = 1
AND p.IsDisabled = 0
And p.CanSale = 1
AND ii.InventoryID IN (' + #OrderList + ')
group by ii.ProductId, p.Name, p.PrimaryImageID, p.ProductNumberLabel, p.ProductNumber, c.Name,p.SalePrice,u.unitname,u.UnitID
having ISNULL((SUM(ii.[QuantityOnHand]) - SUM(ii.[QuantitySold])), 0) > 0
Order by p.ProductNumber, p.Name, c.Name '
EXEC(#SQL)
PRINT(#SQL)
END
END

Resources