How to get exact match from data row using Sql query - c#

Hello i've datarow (IDs) as
12?15?6?11?51?
1?15?6?11?51?
&
I want to search numbers which is equal to 1 (id). For That When i used
%1% this will return match result as both rows
%1?% this will return match result as both rows
%?1?% this will return match result as null
%?1% this will return match result as both rows
the result should be only 2nd row for ID 1.
Please give proper query for this.
Thanks.

SELECT * FROM TableName WHERE ID LIKE '1?%' OR ID LIKE '%?1?%'

SELECT * FROM TABLE WHERE ID LIKE '1?_%' ;
This will work meaning if you contain starting with 1?

You can use
CREATE TABLE T(
ID VARCHAR(45)
);
INSERT INTO T VALUES
('12?15?6?11?51?'),
('1?15?6?11?51? &');
SELECT *
FROM T
WHERE ID LIKE '[1][^0-9]%';
Returns:
+-----------------+
| ID |
+-----------------+
| 1?15?6?11?51? & |
+-----------------+
Demo

Related

SQL COUNT(Column) Counts also the null value which is wrong

I'm creating a total details in my project but I'm having a problem regarding the "COUNT" in my query. It also calculates the null. What I want is, count the column with values only other than that, the query will not count the null column.
Here's my code
SELECT COUNT(columnName) as TotalColumnValue FROM tblName
| columnName|
| value|
| |
| value|
| value|
so the result count would be 3 and not 4 because the value is null.
Thank you in advance.
Actually, a IS NOT NULL condition like mentioned in all the answers is not necessary since count(columnName) will not count null values. So basically it enough to just filter empty string values and just specify the column in the count.
SELECT COUNT(columnName) as TotalColumnValue
FROM tblNam
WHERE columnName <> ''
Note -> to the question you've asked on the comments. <> means != or in words - NOT EQUAL
If the value is really NULL, then COUNT should be excluding that row. Maybe it's not NULL but an empty string''. Try adding a NULLIF in your column:
CREATE TABLE tbl(columnName VARCHAR(10) NULL);
INSERT INTO tbl VALUES ('value'), ('value'), ('value'), ('');
SELECT COUNT(NULLIF(columnName, '')) FROM tbl;
Or you can filter for empty strings:
SELECT COUNT(columnName) FROM tbl WHERE columnNameIS NOT NULL AND columnName <> ''
Adding where function solve your issue. :)
SELECT COUNT(columnName) as TotalColumnValue FROM tblName where columnName is not null
If you want the number of different values (not counting repeating values) use
SELECT DISTINCT COUNT(columnName) AS TotalColumnValue FROM tblName WHERE columnName IS NOT NULL
You need to exclude both NULL and empty string ''.
SELECT COUNT(columnName) as TotalColumnValue FROM tblName
WHERE columnName <> '';

Combining Characters with Id Field

I'll create an Issue table in an MVC5 application and I want to use special code for each type of the issues as below:
For IT related questions INF-0001, INF-0002, ...
For General type of questions GEN-0001, GEN-0002, ...
As I use all the issues on the same table, I think it is better to store the ID numbers as INF-0001, GEN-0001, ... etc. In that case should I use string as the data type of ID column in MSSQL? Or what is the best approach in order to store Id's with their related codes? I also think of using GUID, but I am not sure if it is possible. Thanks in advance.
I suppose it's better create separate field for your custom names. So your table will have int Id (Primary Key) field and CustomName varchar(100) or nvarchar(100) type (If you use unicode characters) field with your custom names.
It will be better for perfomance to use int as Id if you will JOIN your file table with others. If you want to search values in this field and it is slow just create INDEX.
You could have a general issue id and a category, for example:
Table: Issue
------------------------------------
IssueID | CategoryID | CategoryIndex
------------------------------------
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 1 | 3
Table: Category
-----------------------------
CategoryID | Prefix | Name
-----------------------------
1 | INF | IT
2 | GEN | General
Then you calculate the issue number when querying these tables.
You can store the calculated number in a table if you want to keep track of the issue number in case of a change in the database (ex: the prefix for IT related questions changes from INF to IT)
Now that you have a good schema, how do you keep control of the category sequence on the issues table? Check this out:
DECLARE #categoryID INT
DECLARE #nextSequence INT
SET #categoryID = 1 --You'll have to change this!
SELECT #nextSequence = i.CategoryIndex
FROM Issue i
WHERE i.CategoryID = #categoryID
SELECT COALESCE(#nextSequence, 0) + 1 as 'NextSequence'
You can turn that into a stored procedure (NextSequence, maybe?) that receives an INT as parameter (the category ID) and returns another INT as result (the CategoryIndex for the new issue).
Finally, to create your full code:
SELECT
i.IssueID
, c.Prefix + '-' + RIGHT('0000' + CONVERT(VARCHAR(4), i.CategoryIndex), 4) as 'IssueCode'
FROM Issue i
INNER JOIN Category c ON i.CategoryID = c.CategoryID

Duplicate Records when they should be unique

I have a table that I'm trying to query using Linq to SQL
The table is very simple it has 5 columns:
- PersonID
- ADID
- Name
- PlaceID
- PlaceName
I have 2 records in my table and they have the same PersonID in both records but different PlaceID and PlaceName values:
001 | 001 | Person X | P01 | Place 1
001 | 001 | Person X | P02 | Place 2
When I query this in SQL I get exactly the 2 rows:
select * from myTable where PersonID = '001'
However, when I try to do it in LINQ:
List<myTable> PersonInfo = (from myInfo in db.myTable
where myInfo.PersonID == "001"
select myInfo).ToList();
I get a count of 2 in PersonInfo but they are the same record. What am I doing incorrectly?
What I found out was that 1st Entity Framework needs a primary key to operate correctly. After researching the table I was using I found out that there was a primary key but it was a combo key So once I put "Entity Keys" on both columns my select statement returned the correct data.
Thanks to #GertArnold and everyone else that helped me on this problem!

Sum of a particular column using LINQ

Using the below mentioned query I am getting the all the values of a column called
promotionValue . I want to get the sum of all the values of *matched *
var matched = from table1 in dvtempPropertyRoomRatePromotion.ToTable().AsEnumerable()
join table2 in dvPropertyRooms.ToTable().AsEnumerable() on
table1.Field<DateTime>("RateDate") equals table2.Field<DateTime>("RateDate")
where table1.Field<DateTime>("RateDate") == table2.Field<DateTime>("RateDate")
select table1.Field<string>("promotionValue");
You need to parse the string to int or decimal:
var matched = from r1 in dvtempPropertyRoomRatePromotion.ToTable().AsEnumerable()
join r2 in dvPropertyRooms.ToTable().AsEnumerable()
on r1.Field<DateTime>("RateDate").Date equals r2.Field<DateTime>("RateDate").Date
select decimal.Parse(r1.Field<string>("promotionValue"));
decimal sum = matched.Sum();
Note that i've also changed some other things like the redundant where (since you've already joined these tables) or the Date property of DateTime.
Apart from that
why do you need the DataView at all? ToTable creates always a new DataTable. Why don't you use Linq-To-DataSet for all? I assume you've used the DataView for filtering, use Enumerable.Where instead. That would be more consistent, more efficient and more readable.
why is the column promotionValue a string? You should store it as a numeric type.
Here I m putting on simple query for sum of the two column of the different table.
SELECT
res.Date
,res.Cost
, res.Cost+res_con.Cost
FROM [ExpenseMst] res
inner join [ExpenseMst_2] res_con on res_con.ID =res.ID
Date | cost 1 | cost 2| total
2014-03-04 | 5200 |5200 |10400
2014-03-04 | 5012 |5012 |10024
2014-03-22 |100 |100 |200
2014-03-13 |25 |25 |50
2014-02-22 | 120 |120 |240
I hope it is useful..
:)
you can do
int sum = 0;
foreach(int match in matched)
{
sum = sum + match;
}

I want to search in SQL Server with must have parameter in one colunm

I am using c# and SQL Server 2008.
I have table like this
id | propertyTypeId | FinishingQualityId | title | Description | features
1 1 2 prop1 propDEsc1 1,3,5,7
2 2 3 prop2 propDEsc2 1,3
3 6 5 prop3 propDEsc3 1
4 5 4 prop4 propDEsc4 3,5
5 4 6 prop5 propDEsc5 5,7
6 4 6 prop6 propDEsc6
and here is my stored code (search in the same table)
create stored procdures propertySearch
as
#Id int = null,
#pageSize float ,
#pageIndex int,
#totalpageCount int output,
#title nvarchar(150) =null ,
#propertyTypeid int = null ,
#finishingqualityid int = null ,
#features nvarchar(max) = null , -- this parameter send like 1,3 ( for example)
begin
select
row_number () as TempId over( order by id) ,
id, title, description,
propertyTypeId, propertyType.name,
finishingQualityId, finishingQuality.Name,
freatures
into #TempTable from property
join propertyType on propertyType.id= property.propertyTypeId
join finishingQuality on finishingQuality.id = property.finishingQualityId
where
property.id = isnull(#id,property.id ) and proprty.PropertyTypeId= isnull(#propertyTypeid,property.propertyTypeId)
select totalpageconunt = ((select count(*) from #TempTable )/#pageSize )
select * from #TempTable where tempid between (#pageindex-1)*#pagesize +1 and (#pageindex*#pageSize)
end
go
I can't here filter the table by feature I sent. This table has too many rows I want to add to this stored code to filter data for example when I send 1,3 in features parameter I want to return row number one and two in the example table I write in this post (want to get the data from table must have the feature I send)
Many thanks for every one helped me and will help
Sending a delimited list of values to match with a delimited value in a column will generally get you into trouble as the only way to do it is to split each value out from the string. (Also why indexing them is pointless)
You should create an additional table containing the id from your property table & a row for each feature;
property_id feature
----------- -------
5 5
5 7
Then matching is much simpler. You can send the procedure the list of features you want to match ideally using a table valued parameter or alternatively a table function.

Categories

Resources