How Do I Exclude Null Fields?
Apr 28, 2006Is there a way to write a select statement that will pull only fields that are not null?
View 2 RepliesIs there a way to write a select statement that will pull only fields that are not null?
View 2 Repliesi have a query:
select ordernumber,amount from orders
where ordernumber is not null
but i am getting some results where, ordernumber is still blank
ORDERNUMBER Amount
11 1200
12 500
400
15 600
how do i make sure that the fields where order number is blank does not comes in the result.
Ashley Rhodes
Is there any way of excluding an entire row if a particular field contains a null value? Even if other fields in the row aren't null... This is in SQL Server 2005
View 2 Replies View RelatedI'm new to MS SQL server. Is there a select statement that will include fields that are not null?
View 2 Replies View RelatedI have some data from SQL server which contains NULL values for certain fields. I have to create a chart with sum of a field. There is no category and series groups, we are just showing the total sum of a field in chart. Since I have NULL in my source data, nothing is displayed in the chart. I cannot exclude this record from dataset as I have to use this record for other charts. I have to do some filtering in the chart area itself. I have given IsNothing() in the filter of chart properties. It does not work for me. Even I tried to give IsNothing() in the exp of Sum() .
View 6 Replies View RelatedHi all,
is it possible to exclude empty records from an ADSI QuerySelect?
I got a query like
Code SnippetSELECT objectGUID FROM OpenQuery(ADSI, 'SELECT objectGUID FROM ''LDAP://DC=whatever,DC=domain,DC=org'' where objectClass = ''User'' AND objectCategory = ''Person''')
and would like to have it like
Code Snippet
SELECT objectGUID FROM OpenQuery(ADSI, 'SELECT objectGUID FROM ''LDAP://DC=whatever,DC=domain,DC=org'' where objectClass = ''User'' AND objectCategory = ''Person'' AND homeDirectory IS NOT NULL')
or
Code SnippetSELECT objectGUID FROM OpenQuery(ADSI, 'SELECT objectGUID FROM ''LDAP://DC=whatever,DC=domain,DC=org'' where objectClass = ''User'' AND objectCategory = ''Person'' AND NOT(homeDirectory = NULL) ')
The problem is that I can only perform a query like
Code SnippetSELECT objectGUID FROM OpenQuery(ADSI, 'SELECT objectGUID FROM ''LDAP://DC=whatever,DC=domain,DC=org'' where objectClass = ''User'' AND objectCategory = ''Person'' AND NOT(homeDirectory = '''')')
which results in the error
"Could not fetch a row from OLE DB provider 'ADSDSOObject'."
There are many objects which do have a homedirectory, though, and therefore should be fetched.
Any comments or hints on where my error hides?
I know I could go on fetching all objects and exclude the unwanted ones later on but I'd simply run into the limitation of data records LDAP would provide me with.
Thanks in advance!
Regards,
caracol
Hi
I have stupid users... who doesn't?! They have entered carriage returns as a whole value in some fields, that is, the field contains nothing more than a carriage return.
I really need to treat these cases as nulls and have successfully removed whole fields of nothing but spaces by using the LTRIM(RTRIM()) construct. Unfortunately, this doesn't deal with carraige returns. Even CASTing and CONVERTing to varchar and then using LTRIM(RTRIM()) doesn't work.
Does anyone know how I can elegantly get around this problem other than my best guess below:
Best guess pseudo code:
IF count of field is greater than 1 THEN probably a full sentence so ignore ELSE SUBSTRING first character and if CHAR(10, etc) then treat as NULL.
Here's some code that reconstructs the problem:
select datalength(char(13)) CarriageReturnVisible
, datalength(ltrim(rtrim(cast(char(13) as varchar)))) [This Don't Work]
Cheers - Andy
I wrote a select statement, I only want to see orders with max lastUpdatedOn date of 14 days and older. Now my results show dates with all orders of 14 days and older (which is OK), but all others are displayed in the "Uitgifte" column as "NULL". But those orders should not be displayed at all.
selectdistinct ProductionHeader.ProdHeaderOrdNr,
ProductionHeader.PartCode,
ProductionHeader.Description,
ProductionHeader.Qty,
(select max (ProdStatusLog.ProdStatusCode)
[code]...
how can i write a SQL query that will pull all records that are equal to NULL??
View 1 Replies View RelatedI am working on Sql Server 7.0 with a group of Visual Basic programmers that have made the following request:
1.They want all decimals/integer fields in the database to default to 0(zero).
Is there an way to do this for all fields instead of on an individual basis?
2.They don't want a null returned on any character string field.
What is the best way to take care of these 2 requests? Thanks in advance.
Karen Suenram
Hi,
I have a query like this one
SELECT expense_id, CAST(expense_id AS char(10)) + ' - ' + CAST(trip_km AS char(5))+ ' - ' + CAST(expense_amount AS char(5)) + ' - ' + charge_centre AS ExpenseDesc
If charge center is null, I need to ignore this field. How can I achieve this? The reason is that if any of the field is null, it will return ExpenseDesc as null.
Thanks
Here is the problem that I am struggling with. The structure is:
States: StateID, StateName
Counties: CountyID, CountyName
Cities: CityID, CityName
Zips: Zip, StateID, CountyID, CityID
Regions: RegionID, RegionName
Region_Data: RegionID, StateID, CountyID, CityID
The thing about the region is that it can be defined by states only, in which case CountyID and CityId are NULL, can be defined by Counties too, in which case only CityID is NULL or it can be defined up to City level, in which case all 3 are set to something. Example, Northeast would be all cities from northeast, but Pocono would be just some counties in PA, and so on...
The issue is now selecting all cities that belong into a region... Normally I would join the Zips table with the Region_Data table and retrieve all CityIDs... The issue is that, as I said, the CountyID and CityID might be null for some records, so I am not sure how to retrieve them?
I came up with one idea in which I create 3 temporary tables and I select in them all the records that have 1) only state, 2) only state and county, 3) all 3, then I join each and I union the results...
But I am wondering if there is a way to do the select in one shot?
Any idea? I appreciate your help,
Thank you,
Iulian
Regards,
Iulian
How can I make empty cells show NULL on my table? Some cells show NULL others won't. Does this mean that they have contents?
The reason being is that, when I use the code
Select *
From Employees
Where JobDescription1 Like '%montly%'
Those with empty jobdescription1 show with the legitimate results.
Any help please?
Thanks!
Im trying to use MS SQL server mananagement studio to greate a view to recive information from my database.
The problem i have is that i include a tabel where a post have "Null" then that post will not be shown i my qustion/View.
How can i make soure that i get all the post even if they have "null" in a field where it do not mather(its not a Key)
Greatful for very fast, help. Need this to be solved tomorrow :-(
Mitmit
Requirements:
1) Cannot have results in which both m.homephone & d.homephone are both null, or both m.workphone & d.workphone are both null in the result set
2) We also do not want to see any combos where one homephone is null and the other has only the char 0....same for workphone...no null & 0 combinations.
e.g.
m.homephone d.homephone
null 0
0 null
The phone fields are varchar
I know this is hidiously wrong but is my first sloppy attempt at best:
select m.number, m.homephone as master_homephone, d.homephone as debtor_homephone, m.workphone as master_workphone, d.workphone as debtor_workphone
FROM master m
INNER JOIN debtors d ON d.Number = m.number
where (d.homephone <> m.homephone OR d.workphone <> m.workphone)
AND (d.homephone IS NOT NULL AND m.homephone IS NOT NULL)
AND (d.workphone IS NOT NULL AND m.workphone IS NOT NULL)
AND NOT ((d.homephone IS NULL AND m.homephone = '0') OR (d.homephone = '0' AND m.homephone IS NULL))
AND NOT ((d.workphone IS NULL AND m.workphone = '0') OR (d.workphone = '0' AND m.workphone IS NULL))
Hi there,
I have a fairly generic question regarding database design.
I am working on my first database using SQL Express.
I am testing the database by inserting records into the pre defined tables.
Sometimes I forget to input text into a non null field. When
this happens it displays an error and then skips a few rows
which makes my row numbering messy. For example say I have
Row 1, Row 2 Row 3 all nicely formatted but on Row 4 I make a mistake
this row then disapears and their is gap between 3 and 5 where 4 was.
Although I am just testing, I was wondering what happens in a real
scenario if an inexperienced data input person makes a few mistakes it
makes the database numbering systems look bad. In this case
is it common to make most fields NULL to allow for admin errors??
I have a result set stored in a temporary table variable. The fields need to have heirarchy when they finaly get displayed to the user. I need to replace the repeating fields per group with NULL and leave out only one set of unique records per group.
I want to do something like this- make the fields in red NULL while leaving out the ones in green.
{ Col.Group I } { Col. Group II }
Col1 Col2 Col3 Col4 Col5
------- ------- ------- ------- -------
ValA ValA2 ValA3 ValA40 ValA50 {
ValA ValA2 ValA3 ValA40 ValA50 Row. Group A
ValA ValA2 ValA3 ValA41 ValA51 }
ValB ValB2 ValB3 ValB40 ValA50 { Row. Group B
ValB ValB2 ValB3 ValB41 ValA51 }
I was able to achieve this by using @@ROWCOUNT with in a while loop by performing one UPDATE at a time (SET ROWCOUNT = 1). But i have to run Count(*) each time I loop through the update query to figure out the remaining number of rows I have per group as I need to leave out one untouched. But the Count function is taking too much time and I'm having performace issues.
Any idea how I might be able to do this in my stored proc. efficiently?
Thanks,
Samtadsh
Hi all
I have a calculated fields in report designer such as a + b + c + d. In sql server if I run this query
select a + b + c + d from table1
and any of a,b,c or d is null, the result is null.
whereas in calculated fields, it does not return null but infact ignores the null value and treats it as zero.
I want my calculated field to be null if any of the values are null.
Is it possible? I cannot use the isNothing function because I have too many fields and it will be quite cumbersome.
Thanks
I'm using SQL Server Express and am trying to import a CVS file. The CVS file contains a string field (named DAS) that represents a Date. This field can be null.
I've tried using the DTS Wizard to import this CVS file and convert the DAS field to a Date, which works great until it hits a record with a NULL DAS field. It then throws a convertion error.
Still using the DTS Wizard, I've changed the DataType of the DAS field in the Source file to [DT_DATE], it works fine but all the null dates are converted to 12/30/1899.
Is there a way (DTS Wizard or something else) that will allow me to import these CVS files with null Date fields and keep them as null in SQL Server table.
Thanks for any help,
Jon
Hey everyone,
This is probably a very simple question, but I am just stumped. I am storing different name parts in different fields, but I need to create a view that will pull all of those fields together for reports, dropdowns, etc.
Here is my current SELECT statement:
SELECT m.FName + SPACE(1) + m.MName + SPACE(1) + m.LName + ', ' + m.Credentials AS Name,
m.JobTitle,
m.Company,
m.Department,
m.Address,
m.City + ', ' + m.State + ' ' + m.Zipcode AS CSZ,
m.WorkPhone,
m.FAX,
m.Email,
c.Chapter,
m.Active,
s.Sector,
i.Industry
FROM tblMembers m
LEFT OUTER JOIN tblChapters c
ON m.ChapterID = c.ChapterID
LEFT OUTER JOIN tblSectors s
ON m.SectorID = s.SectorID
LEFT OUTER JOIN tblIndustries i
ON m.IndustryID = i.IndustryID
WHERE m.DRGInclude = 1
My problem is that I don't know how to test for NULL values in a field. When you concatenate fields that contain NULL values, the entire contactenated field returns NULL. I am not aware of an IF statement that is available within the SELECT statement.
The first thing I would like to accomplish is to test to see if MName contains NULL. If it does I do not want to include + SPACE(1) + m.MName in the clause. Then, if Credentials contains NULL I do not want to include + ', ' + m.Credentials in the clause.
Can someone tell me what I am missing? Is there a function that I can use for this?
Thanks,
I using Visual Web Designer Express (with Visual Basic), with a SQL Server 2000 database. I have a prototype application running satisfactorily using code that builds queries, but I'm now trying to rebuild the application "properly" using three-tier architecture. I have been following the principles of Scott Mitchell's tutorials. I have created an database .xsd with a table adaptor, and replaced the rather grotty query-building code in the business layer with better code referencing the table adaptor. Thus where the first version had code: -
Dim queryString As String = "SELECT * FROM NZGDB_User WHERE USRid = '" & Userid & "'" Dim message As String = "" Dim Found As Boolean = False Try Using connection As New SqlConnection(GDB_AppSettings.Connection) Dim command As New SqlCommand(queryString, connection) connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
If reader.Read() Then Found = True _USRid = reader("USRid") _USRPassword = reader("USRPassword") _USREmail = reader("USREmail") _USRTitle = reader("USRTitle") _USRName = reader("USRName") _USRRole = reader("USRRole") If IsDBNull(reader("USRAgreedConditions")) = False Then _USRAgreedConditions = reader("USRAgreedConditions") End If End If reader.Close() End Using Catch ex As Exception If Left(Err.Description, 68) = "An error has occurred while establishing a connection to the server." Then Return "Cannot open database to logon" Else Return Err.Description End If End Try
the new version is much more elegant: -
Dim taUser As New NZGDBTableAdapters.NZGDB_UserTableAdapter()
Dim tbUser As NZGDB.NZGDB_UserDataTable = taUser.GetUserByUserid(userid) If tbUser.Count <> 1 Then ' Anything other than 0 or 1 should be impossible Return "User not found" End If
Dim trUser As NZGDB.NZGDB_UserRow = tbUser(0) _USRid = userid _USRPassword = password _USREmail = trUser.USREmail _USRTitle = trUser.USRTitle _USRName = trUser.USRName _USRRole = trUser.USRRole _USRAgreedConditions = trUser.USRAgreedConditions
However, there is a problem. The database field USRAgreedConditions is a Datetime field that can be null. The new version works perfectly when it is NOT null, but throws an exception: -
System.Data.StrongTypingException was unhandled by user code Message="The value for column 'USRAgreedConditions' in table 'NZGDB_User' is DBNull." Source="App_Code.wt2vzoc1" ....
There is no point in writing: - If Not IsDBNull(trUser.USRAgreedConditions) Then _USRAgreedConditions = trUser.USRAgreedConditions End Ifbecause the exception occurs within the automatically-created code in the data access layer. I tried changing the Nullvalue property of the field USRAgreedConditions in the table adaptor, but the only valid option is (Throw Exception) unless the field is a String. Of course USRAgreedConditions is a Datetime field, so I can't change the property.
It seems that my only options are: -1. To stick with the old query-building code. But this doesn't give me the advantages of a proper 3-tier architecture2. To change the generated code in wt2vzoc. This MUST be a bad idea - surely I should leave this code untouched. Besides, what if the table adaptor has to be regenerated when I change the table design?3. Code a Try block within the business layer: - Try _USRAgreedConditions = trUser.USRAgreedConditions Catch ex As Exception _USRAgreedConditions = Nothing End Try
This seems to work OK, but seems less elegant than the original code in the old version: - If IsDBNull(reader("USRAgreedConditions")) = False Then _USRAgreedConditions = reader("USRAgreedConditions") End IfIs there a better way?
Hi, how do i do a select statement with asp.net to return a record if a field is null. I have the following code:
SqlCommand cmd = new SqlCommand("SELECT * FROM Categories WHERE ParentId = @ParentId", cn);.Parameters.Add("@ParentId", SqlDbType.Int).Value = parentId != null ? (object) parentId : DBNull.Value;cn.Open();
The variable parentId is a nullable int. However when i pass in a null value it doesn't return anything even though there are records in the database that have a null value for the ParentId field.
Appreciate if someone could tell me what i am doing wrong. Thanks
hi,
I've done Googling and forum hunting but haven't had success finding a simple answer... My table schema is such that it requires the (int) LinkedItemID field to be nullable but still those fields which are set must not be duplicates. I see constraint is out of question and also identity doesn't seem to fit since I'm not using autofill for this particular field. Is there some other way doing this on Sql Server 2005?
Thank you.
On my aspx page I have a basic sqldatasource and gridview - both were set up using the wizards. The SQL Server 2000 database table that the sqldatasource is querying has some fields in it that are set to not allow nulls, however, the gridview control is not displaying all of the fields in the table - including some of the non-null fields.
My problem is, when I run an insert on the table from my aspx page, I get an error that says: "Cannot insert the value NULL into column 'ColumnName', table 'TableName'; column does not allow nulls. INSERT fails. The statement has been terminated."
The 'ColumnName', as you may have guessed, is one of the aforementioned columns that doesn't allow nulls, but isn't in the GridView.
How can I do an insert on this table without messing with the non-null fields. Those fields are relevant to the purposes of the gridview, so I don't want to display them, let alone allow editing of them.
Any suggestions on my options would be greatly appreciated!
Thanks
Capella07
If I query sql server I get 10 results. But when I use if (myReader.Read()) I get only 7 results. I found that there was a Null field in the DB. I changed it and it worked.
The problem is I don't want to touch the database and set all null fields. There must be a way to get all results including the Null using sqlDataReader so that if (myReader.Read()) is used it does the right comparison.
// This code is called 10 times with a select * from where item="xxx"
P21Conn.Open();
SqlDataReader myReader = cmd.ExecuteReader();
if (myReader.Read()) {
thanks
Rod
How can I enter NULL manually in one of the rows in Sql Server database. Those rows does not contain any data.
View 3 Replies View RelatedI know I am missing something basic, here.
I have a date field in a table. The field is 'allowed Nulls'. When a certain thing happens in the program, the date is filled in.
At various times, I need to do a query to find all the rows that have no dates entered.
What do I use in my where clause? SQL server does not like 'where date = null.'
Thanks,
Judith
Hi:
I used this statement, select * from table1 where date1 = null, in SQL Query window and got a few records back. Now, I used the same statement in my VB 5 code and no record is found. How do I select all the records in table1 which do not have values in field date1? Thanks for the help.
-Nicole-
Hi,
When I try to insert a new record into a table that has a datetime field that allows nulls, a default 01/01/1900 date is inserted instead of null. I recreated the table and set the datatype to smalldatetime and I still get the error. What have I missed?
Can someone help me with this :
Case WHEN ISNULL (dbo.BLH.n1name,'NOTHING')= 'NOTHING' then dbo.BLH.coname else dbo.BLH.n1name End as CustName
as the strored proc is not returning value when the fileds is blank
cheers
Hi guys, I have made several Access-based CMSs but now I am using SQL Server. I can read the records but my first attempts at writing are resulting in new records (with new ID) but all the fields are null.
I am posting the data from a form to the same page and an if /then statement catches the flag in the URL and runs the update script below. All the field names are correct.
if request.QueryString("add")<> "" then
Dim rsUpdateEntry
Set rsUpdateEntry = Server.CreateObject("ADODB.Recordset")
rsUpdateEntry.Open "SELECT * from generic_country_info" , oConn, 2, 3
rsUpdateEntry.AddNew
rsUpdateEntry.Fields("title1") = Request.Form("title1")
rsUpdateEntry.Fields("body1") = Request.Form("body1")
rsUpdateEntry.Fields("title2") = Request.Form("title2")
rsUpdateEntry.Fields("body2") = Request.Form("body2")
rsUpdateEntry.Fields("title3") = Request.Form("title3")
rsUpdateEntry.Fields("body3") = Request.Form("body3")
rsUpdateEntry.Fields("title4") = Request.Form("title4")
rsUpdateEntry.Fields("body4") = Request.Form("body4")
rsUpdateEntry.Fields("title5") = Request.Form("title5")
rsUpdateEntry.Fields("body5") = Request.Form("body5")
rsUpdateEntry.Fields("image1") = Request.Form("attach1")
rsUpdateEntry.Fields("image2") = Request.Form("attach2")
rsUpdateEntry.Fields("image3") = Request.Form("attach3")
rsUpdateEntry.Fields("image4") = Request.Form("attach4")
rsUpdateEntry.Fields("image5") = Request.Form("attach5")
rsUpdateEntry.Fields("country") = Request.Form("country")
rsUpdateEntry.Fields("dest_url") = Request.Form("dest_url")
rsUpdateEntry.Update
rsUpdateEntry.Close
Set rsUpdateEntry = Nothing
end if
Thanks
Mark
Hello folks,
I am stuck at a problem, not sure on how to go about writing a query that will return as a percentage the number of fields in a row that are null.
For instance, a row from my table:
Row1 : field1 field2 field3
If field3 is empty or null, my query should return 67%.
So far I have gotten the number of fields:
select count(1) from information_schema.columns where table_name='myTable'
I could loop through the fields but I am sure there is a simpler way of doing it, I have seen something simpler in the past with some builtin SQL functions. I am using MS SQL 2005.
Thanks for your help
Mike
I am attempting to update a table that drives a report. The report is at the order level. An order can have several types of demand (revenue $): Ship and/or Backordered. When I update one of these demand fields on the report table, I would expect those orders that have that type of demand to update, and those orders that don't have that type of demand to remain at their current value ($0 in this example which is the table default). But what is happening is that orders that don't have that type of demand are changing to NULL. What am i doing wrong with my update statement that is causing this?
Code:
CREATE TABLE #sales(
OrdNo int,
StatusGrp varchar(10),
Demand decimal(10,2)
)
INSERT INTO #sales
VALUES (1,'Ship',100.00)
[Code] .....