Can SQL Assign Zero When NULL Is Returned From A Sub-query?
Dec 26, 2006
Hi Folx,
I am new to
SQL Server. I am rolling summed values from table profile to two columns in table txn. When the value for one (not necessarily both...) column is null, can that value be translated to zero? Or must I write a procedure or use a cursor?
Versions:
Microsoft SQL Server Integration Services Designer
Version 9.00.1399.00
Microsoft SQL Server Management Studio
9.00.1399.00
For example, when version_count for a particular transaction_id is null in the profile table but profile_count has summable integers, how do I update the version_count to zero in the same pass that I update the profile_count?
update txn
set
version_count =
(
select
sum(a.version_count)
from
profile a
where
a.transaction_id=txn.transaction_id
and
a.extraction_date=txn.extraction_date
and
txn.version_count is null
),
profile_count =
(
select
count(*)
from
profile a
where
a.transaction_id=txn.transaction_id
and
a.extraction_date=txn.extraction_date
and
txn.profile_count is null
)
I run a stored procedure for which I have a return variable. The stored procedure returns the ID of a row in a table if it exists:
m_sqlCmd.ExecuteScalar();
The m_sqlCmd has been fed an SQLParameter with direction set to output. When the stored proc returns, I want to test it. Now when there IS a row it returns the ID ok. When the row doesn't exist, in my watch I have:
m_sqlParam.SqlValue with value {Null}
I can't seem to work out how to test this value out. I've tried several things but none seem to work.
This line compiles ok, but the following runs into the IF statement as if the SqlValue is null??
if (m_sqlParam.SqlValue != null).... {
// I'm here!! I thought the watch says this is null??? }
Sorry if this is obvious, but I can't work this one out!!
I have this query and I tried this but am getting the error for the case statement when I assign the nulls to a 0:
The error is they data types of the result expression of a CASE expression are not compatible.
SELECT 'C' as account, FUND_dim.fund_cde as FUND, case when sum(BRKGRPTT.daily_brkg_fact.accum_unit_cnt) is null then '0' else sum(BRKGRPTT.daily_brkg_fact.accum_unit_cnt) end as Units_Purchased FROMFUND_DIM left outer join BRKGRPTT.daily_brkg_fact on FUND_DIM.FUND_ID_NUM = BRKGRPTT.daily_brkg_fact.FUND_ID_NUM and BRKGRPTT.daily_brkg_fact.SEP_ACCT_ID_NUM <> 1 left outer join SEP_ACCOUNT_DIM on BRKGRPTT.daily_brkg_fact.sep_acct_id_num = SEP_ACCOUNT_DIM.sep_acct_id_num group by BRKGRPTT.sep_account_dim.sep_acct_cde, BRKGRPTT.fund_dim.fund_cde order by FUND_dim.fund_cde
I have a column with int data type.. i am trying to assign this column to a variable ( int) in For Each Loop..but it keeps giving me an erro
The type of the value being assigned to variable "User:ubcontractor_Key" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object.
Am i getting this error becasue the column has NULL value?. how can I resove this probelm?
I've got a query on a particular table returning an odd result:
SELECT DISTINCT WorkStation FROM Invoice WHERE WorkStation Is Not Null ORDER BY WorkStation
This query returns the rows I'd expect plus a null row. This doesn't happen in databases at other sites, or in other tables at this site. The following query behaves as I'd expect returning only non-null AccountNumbers.
SELECT DISTINCT AccountNumber FROM Suppliers WHERE AccountNumber Is Not Null ORDER BY AccountNumber
I can't reproduce these results on another site on a table of the same structure, or on another table at this site.
Any suggestions as to what might be going on?
Pertinent info: --- select @@Version
Microsoft SQL Server 2000 - 8.00.760 (Intel X86) Dec 17 2002 14:22:05 Copyright (c) 1988-2003 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 1) --- dbcc checkdb Abridged result: CHECKDB found 0 allocation errors and 0 consistency errors in database 'POS'. --- SELECT * INTO #Inv FROM Invoice
SELECT DISTINCT WorkStation FROM #Inv WHERE WorkStation Is Not Null ORDER BY WorkStation
Does not reproduce this problem (and so is a probable fix) but the questions remains, what causes this?
I have a strange problem. I have some code that executes a sql query. If I run the query in SQL server query analyzer, I get a set of data returned for me as expected. This is the query listed on lines 3 and 4. I just manually type it into query analyzer. Yet when I run the same query in my code, the result set is slightly different because it is missing some data. I am confused as to what is going on here. Basically to examine the sql result set returned, I write it out to an XML file. (See line 16). Why the data returned is different, I have no idea. Also writing it out to an XML file is the only way I can look at the data. Otherwise looking at it in the debugger is impossible, with the hundreds of tree nodes returned. If someone is able to help me figure this out, I would appreciate it. 1. public DataSet GetMarketList(string region, string marketRegion)2. {3. string sql = @"SELECT a.RealEstMarket FROM MarketMap a, RegionMap b " + 4."WHERE a.RegionCode = b.RegionCode"; 5. DataSet dsMarketList = new DataSet();6. SqlConnection sqlConn = new SqlConnection(intranetConnStr); 7. SqlCommand cmd = new SqlCommand(sql,sqlConn);8. sqlConn.Open();9. SqlDataAdapter adapter = new SqlDataAdapter(cmd); 10. try11. {12. adapter.Fill(dsMarketList); 13. String bling = adapter.SelectCommand.CommandText;//BRG 14. dsMarketList.DataSetName="RegionMarket"; 15. dsMarketList.Tables[0].TableName = "MarketList"; 16. dsMarketList.WriteXml(Server.MapPath ("myXMLFile.xml" )); // The data written to 17. myXMLFile.xml is not the same data that is returned when I run the query on line 3&4 18. // from the SQL query 19. } 20. catch(Exception e) 21. { 22. // Handle the exception (Code not shown)
Here is the scenario, I have 2 stored procedures, SP1 and SP2
SP1 has the following code:
declare @tmp as varchar(300) set @tmp = 'SELECT * FROM OPENROWSET ( ''SQLOLEDB'', ''SERVER=.;Trusted_Connection=yes'', ''SET FMTONLY OFF EXEC ' + db_name() + '..StoredProcedure'' )'
EXEC (@tmp)
SP2 has the following code:
SELECT * FROM SP1 (which won't work because SP1 is a stored procedure. A view, a table valued function, or a temporary table must be used for this)
Views - can't use a view because they don't allow dynamic sql and the db_name() in the OPENROWSET function must be used. Temp Tables - can't use these because it would cause a large hit on system performance due to the frequency SP2 and others like it will be used. Functions - My last resort is to use a table valued function as shown:
FUNCTION MyFunction ( ) RETURNS @retTable ( @Field1 int, @Field2 varchar(50) ) AS BEGIN -- the problem here is that I need to call SP1 and assign it's resulting data into the -- @retTable variable
-- this statement is incorrect, but it's meaning is my goal INSERT @retTableSELECT *FROM SP1
Anyone know how I can null-out the returned values of the PrjMgr field? I have bolded the field in question. Here is the code:
select AgencyId ,ControlNumber ,ISNULL(LLA_AUDITS.PrjMgr,Projects.PrjMgr) as PrjMgr,ISNULL(CASE LEN(datepart(mm, PeriodFinish)) WHEN 1 THEN '0' + CAST(datepart(mm, PeriodFinish) as varchar(2)) ELSE CAST(datepart(mm, PeriodFinish) as varchar(2)) END ,'')As month ,ISNULL(CAST(datepart(dd, PeriodFinish) as varchar), '') As day ,ISNULL(CAST(right(datepart(yy, PeriodFinish),2) as varchar),'') As year ,ISNULL(CAST(left(datepart(yy, PeriodFinish),2) as varchar),'') As century ,custName from LLA_Audits Left Outer Join Projects on controlnumber = prjcode Left Outer Join Customers on Agencyid = CustCode where AgencyId is not null and not(LLA_AUDITS.PrjMgr is null and Projects.PrjMgr is null) and left(controlnumber,2)<>'72' and left(controlnumber,2) <>'13' and (CPAFirmId IN ('0','')or CPAFirmId is null) order by ControlNumber
This should be a simple solution, but it has been a long time since I've done any query writing (mostly in Oracle) and I am stumped, so here goes:
We are in the process of converting Access database to MSSQL with web form front ends.
I have a table, all columns are nullable, and want users to be able to query from a form, which has a field for each column and defaults to a % wild card for the entered value.
I want the users to be able to put any string in any field, and have it return each row that matches that, including rows with null values in the other columns, but not the column with the entered criteria.
Here is a sample of the data:
Code: SQL> select * from test;
COL1 COL2 COL3 COL4 ----- ----- ----- ----- this is a test this is not test this is not this is test too is test too is too is too
7 rows selected.
Now, if I have this SQL run, it will return only rows that have no nulls in any columns:
Code: select col1, col2, col3, col4from test where col1 like'th%' and col2 like '%' and col3 like '%' and col4 like '%';
COL1 COL2 COL3 COL4 ----- ----- ----- ----- this is a test this is not test this is test too
Now, if I use an OR clause for each column, this mostly works, but the trouble is it will also return rows with null values for the field that has criteria entered in it:
Code: select col1, col2, col3, col4from test where (col1 like'th%' OR col1 is null) and (col2 like '%' OR col2 is null) and (col3 like '%' OR col3 is null) and (col4 like '%' OR col4 is null); COL1 COL2 COL3 COL4 ----- ----- ----- ----- this is a test this is not test this is not this is test too is test too is too is too
The idea is to only select the first 4 rows in the above example.
I was playing with ISNULL in the select clause, but all it does is substitute a string for a null, and I think CASE will do the same thing.
Is there a way I can write this query so it will return rows with NULL values in any column, except the one(column) that has user entered criteria in it?
I'm using SSIS 2005 Enterprise edition, I'm creating a package that reads an excel (xls) file using the "excel source" component, and it dumps the data into an OLEDB destination (a sql server). When I drag the excel source component and create the excel connection to my file the component automatically reads the columns and their datatypes.
The problem is that I have a column which has numeric data and the package uploads as NULL every number that starts with a zero. (note: in excel this column is formatted as "text", despite it has only numbers, because it's the only way excel maintains the left sided zeros).
So I checked the data types by right clicking the excel source component -> show advanced editor and my surprise is that this column's data type is detected as double-precision float, and it doesn't let me change it. URL... but it only works when the first row of data has a number beginning with zero on this column. How to get the data imported correctly?
Hi My webpage contain three dropdown box and one button. One dropdown to choose hospital_id, second dropdown to choose project_id and third dropdown to choose version_no .After choosing these three and when the button is clicked i want to run this sql query INSERT INTO version(project_id,hospital_id,date_created,comments) SELECT project_id,hospital_id,date_created,comments FROM version where version_no=@version_no and project_id=@project_id and hospital_id=@hospital_id. Just i need the code in asp.net 2.0 , VB , when the button is clicked the above query should run and the parameters (values) should take from dropdown box. Could anyone please send the solution for the above problem.
I have the following code which is incomplete. Where it says: txtVendorID = I need it to equal the results of the field VendorID from my query...here is my code. What do I need to add there?
Dim cmdSelect As SqlCommandDim intRecordIDintRecordID = Request.QueryString("RecordID")strConn = ConfigurationManager.AppSettings("conn")conn = New SqlConnection(strConn)cmdSelect = New SqlCommand("spMfgRepListAddaspxByRecordID", conn)cmdSelect.CommandType = CommandType.StoredProcedurecmdSelect.Parameters.AddWithValue("@RecordID", intRecordID)conn.Open()cmdSelect.ExecuteReader()txtVendorID.Text = conn.Close()
I'm trying to find it difficult to use recursice CTEs or better solution for a special request below. There are two tables 1) @sizes serves as a lookup or reference for right drive and 2) @test is sample data with different sizes. Assume that I want to evenly distribute the drive letters from table1 to table2 by checking the size available.
E.g.: for the first record in @test; id = 1 where the size is 50 and it fits in Y: drive -- left over space in Y: = 50
id=2, size 2.5, space available from left over = 50 - 2.5 = 47.5 which again fits into Y: id = 3, size 51, cannot in fit in Y: drive as there is enough space in Y: to allocate (51 > 47.5)
so pick the next drive check on availability again
DECLARE @sizes TABLE (id TINYINT, size DECIMAL(5,2), drive VARCHAR(3)) INSERT INTO @Sizes SELECT 1,100.00,'Y:' UNION ALL SELECT 2,80.85,'Z:'
[Code] ....
-- My output should look like
col1 , val , path A 50 Y: B 2.5 Y: C 51 Z: D 2.6 Y: E 52 Z: F 2.7 Y:
I am not sure if this possible, but I have store procedures that access to multiple databases, therefore I currently have to hardcode my database name in the queries. The problem start when I move my store procedures into the production, and the database name in production is different. I have to go through all my store procedures and rename the DBname. I am just wonder if there is way that I could define my database name as a global variable and then use that variable as my DB name instead of hardcode them?
I have a DTSX package which reads values from a fixed-length text file using a data reader and writes some of the column values from the file to an Oracle table. We have used this DTSX several times without incident but recently the process started inserting NULL values for some of the columns when there was a valid value in the source file. If we extract some of the rows from the source file into a smaller file (i.e 10 rows which incorrectly returned NULLs) and run them through the same package they write the correct values to the table, but running the complete file again results in the NULL values error. As well, if we rerun the same file multiple times the incidence of NULL values varies slightly and does not always seem to impact the same rows. I tried outputting data to a log file to see if I can determine what happens and no error messages are returned but it seems to be the case that the NULL values occur after pulling in the data via a Data Reader. Has anyone seen anything like this before or does anyone have a suggestion on how to try and get some additional debugging information around this error?
I am getting the following results from my query that contains a subquery, but I don't understand why the values in the [Total Volume M_Active_Previous] are being repeated with the same value. I should be getting different values returned for each row like in the [Total Volume M_Active] column.
Why the values are all the same and how I can fix this?
I'm a really beginner about sql2000.During my test I have created the following query. It's works ok until Ido't add the code included in section A, when I add it the i obtain theerror: Cursor not returned from queryAnyone can help me?Thanks Carlo M.set nocount onIF OBJECT_ID('storico_big') IS NULL --- section A begincreate table storico_big( data datetime,bcarrier varchar(20),bda CHAR(30),bzone char(50),bdur int) ;insert into storico_big --- section Aendselect top 10000adetdate,bcarrier,bda,bzone,bdurfrom pp_cdr (nolock)whereadetdate < :data_fin and adetdate > :data_in order by adetdateset nocount off------ end of query
I am executing following script which return more than 1 query/row as there are more than 1 log backup : select @Query = 'RESTORE LOG ' + @dbName + ' FROM DISK=' + '''' +@path+''''+ ' WITH' + ' NORECOVERY, FILE= ' + convert(varchar(10),Position) from #temp where BackupName = 'Log_Backup' and BackupType = 2 and Position> @Diff_Position EXEC(@QUERY)
[Above script restores database with latest Differential backup file and latest log files. ] Now I want to execute this, but @Query don't work for more than one row returned . Can you please suggest me how to execute such query?
I would like to make a listbox only appear if there are results returned by the SQL select statement. I want this to be assessed on a click event of a button before the listbox is rendered.I obviously use the ".visible" property, but how do I assess the returned records is zero before it is rendered?
The query below gets percentage of coils for a location by anneal cycle. It does this correctly (ie, if you change count(*)/b.total to count(*), b.total ... show both columns, the numbers its pulling are correct), but in its current state (trying to divide count by total), it always returns a zero (no decimal values).
If I change that section to : (count(*)*100/ b.total*100)/100, I get integer percentages: no decimals (this is a problem because some records round off to zero). I'm pretty sure this is the entire problem (why I'm getting zeros as written below), but I don't have a clue how to fix it. Is this some kind of server setting that allows the query to only return decimal values or something?
select a.department, a.cycle, count(*)/ b.total percentage from inventory a join (select department, count(*) total from inventory where location not like 'bas%' and archived = 0 and quality_code = 'p' group by department) b on a.department = b.department where a.archived = 0 and a.quality_code = 'p' and location not like 'bas%' group by a.department, a.cycle, b.total order by a.department, a.cycle
I¡¦ve got a table with the following as well as other info:
User ID DirectoryTypeID (int) Region ID (int)
I need to run a query where I could get the region ID, then, in the second column, I¡¦d get all distinct directory types within that region. For example, if I run the query:
Gurus.I do not know if it is possible, but here is what I want to do.I want to allow user to page the SQL result, so he could decides toreturn from row 10 to row 20, or row 100 to 200, without returns thewhole resultset. Every time he sends another request, I do not mind tohit the database again, (I do not want to cache the result in themiddle tier server, scalability issue), and I know that I could achievethis with CURSOR, but unfortunately the FOR XML is not allowed in aCURSOR statement .(I know that I could achieve what I want to do by writing custom codein the middle tier, but I just want to see if there is a way to do thison the database side.)Any comments & suggestion is greatly appreciated.Thanks in advance.(I am using SQL2005)John
In a query in Management Studio, I want to output data to a text file (via Results in text button) without column names and hyphens or dashes, I have searched all SET commands with bad luck because SET FMTONLY OFF do exactly the opposite.
I know this could be a silly question because I have received suggestions in other ways to do that, but I am intrigued If there is a way to prevent column name from being displayed/returned from a query.
@@version yields
Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86) Feb 9 2007 22:47:07 Copyright (c) 1988-2005 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
Hi all, I am writing a select query which produces huge xml data.Now i want to read that data from my web application a save it as xml file. How can i do that. I am using asp.net vb.net.
i have a table and a column called req_id, i have it set as the primary key.. so if i just do SELECT * FROM table, shouldnt the rows returned be sorted by the order that the rows were inserted?
this database was improted from an access database.. when i did that in access it would return the rows in sorted order by the order the row was inserted.. but now in MS SQL, its not sorted in that order.. i can't really tell what type of order it's in