Inserting Few Recordsets Into Temp Table Containing NULL Values
Jul 20, 2005
Hi
I need some help on achieving the following:
I wrote a querie which collects Data out of three Tables, the Result
looks like this:
SET NOCOUNT ON
DECLARE @ROWINT
DECLARE @CURPTNO CURSOR
SET @CURPTNO = CURSOR
FOR
SELECT * FROM TEMP
OPEN @CURPTNO
FETCH NEXT FROM @CURPTNO
INTO @ROW
WHILE (@@FETCH_STATUS = 0)
BEGIN
SELECT ONE.CYNO, ONE.ROLE, ONE.ROL_BEZ, ONE.PTNO, ONE.NOCY, TWO.TEXT
AS NOCY_TEXT
FROM
(SELECT CY.CYNO,
RE.CYNO AS RECYNO, RTRIM(RE.ROLE) AS ROLE, RTRIM(V_ROLE.TEXT) AS
ROL_BEZ,
RE.PTNO AS PTNO, RTRIM(RE.NAME) AS SACHBEARBEITER, RE.NOCY
FROM CY
RIGHT OUTER JOIN
RE ON RE.CYNO = CY.CYNO
INNER JOIN
V_ROLE ON RE.ROLE = V_ROLE.CODE
WHERE (RE.PTNO IN
(SELECT PT.PTNO
FROM PT
WHERE PT.PTNO IN
(@ROW)
AND V_ROLE.LANGUAGE = PT.CLANG
))) AS ONE
LEFT JOIN
(SELECT V_NOCY.CODE, V_NOCY.TEXT
FROM V_NOCY
INNER JOIN
PT ON PT.CLANG = V_NOCY.LANGUAGE
AND PT.PTNO IN (SELECT PT.PTNO
FROM PT
WHERE PT.PTNO IN
(@ROW)
)) AS TWO
ON ONE.NOCY = TWO.CODE
My Problem is, that I need to have all the Resultsets in one Table at
the end.
So my further undertaking was to create a Temp Table with the
expectation to receive all the resultsets in one Step.
INSERT INTO #CYRE_TEMP (CYNO, ROLE, ROL_BEZ, PTNO, NOCY, TEXT)
VALUES
(@CYNO,@ROLE ,@ROL_BEZ ,@PTNO ,@NOCY ,@TEXT)
SELECT @CYNO = ONE.CYNO,
@ROLE = ONE.ROLE,
@ROL_BEZ = ONE.ROL_BEZ,
@PTNO = ONE.PTNO,
@NOCY = ONE.NOCY,
@TEXT = TWO.TEXT
FROM
(SELECT CY.CYNO, RTRIM(RE.ROLE) AS ROLE, RTRIM(V_ROLE.TEXT) AS
ROL_BEZ,
RE.PTNO AS PTNO, RTRIM(RE.NAME) AS SACHBEARBEITER, RE.NOCY
FROM CY
RIGHT OUTER JOIN
RE ON RE.CYNO = CY.CYNO
INNER JOIN
V_ROLE ON RE.ROLE = V_ROLE.CODE
WHERE (RE.PTNO IN
(SELECT PT.PTNO
FROM PT
WHERE PT.PTNO =
@ROW
AND V_ROLE.LANGUAGE = PT.CLANG
))) AS ONE
LEFT JOIN
(SELECT V_NOCY.CODE, V_NOCY.TEXT
FROM V_NOCY
INNER JOIN
PT ON PT.CLANG = V_NOCY.LANGUAGE
AND PT.PTNO IN (SELECT PT.PTNO
FROM PT
WHERE PT.PTNO =
@ROW
)) AS TWO
ON ONE.NOCY = TWO.CODE
I am trying to insert null values into sql server from my access from. I am using sql statement. But it says 'Syntex error in Insert statement'. When i remove null values it works fine? How can I insert null values into a table?
We are using an SQL Server database and seem to be having some problems with inserting null values into numeric fields. The field is set to accept nulls, but when we try and write a record into the database and that field is null, the application craps out on us. Are there any issues that we should be aware of when inserting null values into numeric fields? What might the problem be? Thanks.
When the first TrackCodeid is NULL all remaining NULL TrackCodeid is entered as null in the database table but if the first/prev trackcodeID is not NULL then following null trackCODEID is populated with the prev trackcodeID and not as null in database <TrackCodeId>ABCDEFG</TrackCodeId> All Null TrackCOdeID is populated as ABCDEFG if we remove ABCDEFG and then bulkload all null values are populated if a null trackCODEID is to be inserted the prev trackCODEID must be null and must not contain any value
I am using a DAL and i want to insert a new row where one of the columns is DATE and it can be 'NULL'. I am assigning SqlTypes.SqlDateTime.Null. But when the date is saved in the database, i get the minvalue (1/01/1900) . Is there a way to put the NULL value in the database using DAL????how can i put an empty date in the database? THANK YOU!!!
Hi, I have fields in my table which allow nulls. Is it efficient to not insert anything (the field automatically shows up as null in this case) and leave or store some value into it. The field is a smallint field?
We are writing a C application that is using ODBC to insert recordsinto a database. We have a NOT NULL column that can legitimately havean empty value, i.e. we know the value and it is empty (i.e. a zerolength string).We are using SQLBindParameter() to bind a variable to theparameterized insert statement <<in the form: INSERT INTO table VALUES(?, ?, ?)>>. We are using SQLExecDirect() to process the SQL.We are running into the problem where ODBC is converts the empty (zerolength) string into a NULL value and this errors due to the fact thatthe column is defined as NOT NULL.We do not want to redefine the column as NULL, becasue myunderstanding of the correct usage of a NULL column is to indicatethat a value is unknown or meaningless... in our case we know thevalue (it is empty) and an empty value has meaning within ourapplication.I'm sure that this issue has been seen and address thousands(millions?) of times... any guidance would be appreciated.
Hi, I have a proc, if i run that proc from query analyzer it completes in 12 sec. I want those results to be inserted into temp table. When i try to insert the results from Stored proc to temp table it is taking 5 min.
What could be the cause of the problem? Any help would be greately appreciated. sskris
I have a temp table in my stored procedure when I try to insert into the temp table thro dynamic sql, it says that table has to be defined. What could be the problem. i have added the code below
CREATE PROCEDURE USP_RULE AS declare @TABLE1 table ( SlNo int identity(1,1), EqNum varchar(25),Pointnum varchar(25) ) declare @EqNum varchar(25),@Pointnum varchar(25) DECLARE @STRDBNAME VARCHAR(50) SET @STRDBNAME = 'DB1' EXEC('insert into '+@TABLE1+' select EQNUM,POINTNUM from '+@STRDBNAME+'..TABLE2')
I'm trying to insert any null values into a temp table. I'm storing the ixo_rlt_code as OldRole, and 'Other' as NewRole. I need both the ixo_rlt_code as OldRole and 'Other' as NewRole in the temp talbe in order to run an update I'm writing.
I know a case statement isn't necessary here, but this section is only one small part of a larger script, so I just used it to be consistent, and it will be easier to make any future changes this way. Below is my code and the error message I'm getting...
select ixo_key, ixo_title as Title, ixo_rlt_code as OldRole, CASEWHEN ixo_title is null or ixo_title = '' or ixo_title = ' ' or ixo_title = ' ' THEN 'Other'
END as NewRole
from co_customer (nolock) join co_individual_x_organization (nolock) on ixo_key = cst_ixo_key --and ixo_delete_flag = 0 where cst_delete_flag = 0 and cst_type = 'Individual' and ixo_rlt_code is null
This is the Error Message I get: Server: Msg 515, Level 16, State 2, Line 1095 Cannot insert the value NULL into column 'NewRole', table 'tempdb.dbo.#temp_______________________________________________________________________________________________________________00000001698C'; column does not allow nulls. INSERT fails. The statement has been terminated.
I have an ASP page that opens a recordset on a stored procedure. I've had it in production for over a year, and it usually works fine - subsecond response. However, in the past couple weeks, the recordset open command has intermittently started to return timeout errors. It's very strange: when the timeout occurs, it can be dependably reproduced by opening the ASP page with the same parameter that produced the initial timeout. However, if you pass a different parameter to the procedure, it runs fine! It only times out when using the specific parameter that produced the initial timeout.
Even stranger: If, when attempting to debug it, I use QA to run the sp with the "defective" parameter, the sp invariably runs fine! And subsequent runs of the ASP page start working as well!
I have repeated this process many times in the past couple weeks: receive a report of the timeout error; open the asp page with the parameter that produced the timeout to verify; repeat; open the asp page with a different parameter - works fine; repeat with the initial parameter - timeout; Open QA and run the sp - no problem; refresh the asp page - no more symptom.
The connection to the SQL Server (7.0) uses a specific SQL login for all communications with the server. So all asp pages are logged in under the same name. I thought this might be a connection pooliing issue, so this morning, when the problem occurred, I logged into QA as the special name, but again, there was no problem running the sp from QA.
So - I've run SQL Profiler to track what's going on when the problem occurs and I've discovered the last statement to successfully run. Here is the sp:
/* * File Name: np_GetAvailablePreviews.sql
Returns a list of "reports" available to be previewed, defined as:
date/shift combination with "P" mode and "C" status (if there are Shift records, there must be an All record)
If none exist, check for the existence of accepted (mode = "A") Shift records without a corresponding All record - if so, return an All item for that date
Concatenate <OPTION> tags around each item */
CREATE PROCEDURE np_GetAvailablePreviews ( @DivisionNumber smallint) AS BEGIN set nocount on declare @count int, @datefrom datetime select @datefrom = dateadd(day,-900,getdate()) CREATE TABLE #PreviewReports ( ProductionDate datetime NULL, Shift char(3) NULL )
Insert #PreviewReports SELECT DISTINCT ProductionDate,Shift FROM dbo.LineItems WHERE DivisionNumber = @DivisionNumber AND Mode = 'P' AND Status = 'C' AND productiondate >= @datefrom
-->>>The above command completes successfully according to Profiler
Insert #PreviewReports SELECT distinct t1.ProductionDate, 'All' FROM (SELECT distinct ProductionDate, Shift, Mode, Status FROM LineItems WHERE DivisionNumber = @DivisionNumber AND Shift<>'All' AND Mode='A' AND Status='C' AND productiondate >= @datefrom AND timeperiod IN ('Day','Shift') ) t1 LEFT JOIN (SELECT distinct ProductionDate, Shift, Mode, Status FROM LineItems WHERE DivisionNumber = @DivisionNumber AND Shift='All' AND Mode='A' AND Status='C' AND productiondate >= @datefrom AND timeperiod IN ('Day','Shift') ) t2 ON t1.ProductionDate = t2.ProductionDate WHERE t2.ProductionDate Is Null AND NOT EXISTS (Select * from #PreviewReports where productiondate = t1.ProductionDate and Shift = 'All')
-->>>This one (the one before this comment) starts, but does not -->>>complete
set @count=(Select Count(*) From #PreviewReports)
-->>This one never begins - the ADO command times out
<snipped>
I did not provide a repro script because the problem is so intermittent that I doubted it would do anyone any good.
However if someone feels they want to try to reproduce this, I will attempt to create a repro script for them.
I suspect there is an issue with the temp table, but it's such a moving target that I haven't been able to pin it down.
I need to insert FK information into a temp table using database name and table name as a parameter.
I've been trying different ways, even with global temp table, but still doesn't work. Below is the code showing what I am trying to achieve. I want to avoid global temp table if possible.
IF OBJECT_ID('tempdb..##FKs') IS NOT NULL DROP TABLE ##FKs CREATE TABLE ##FKs ( [ForeginKeyName] [nvarchar](128) NULL, [TableSchema] [sysname] NULL, [TableName] [nvarchar](128) NULL, [RelatedTableSchema] [sysname] NULL,
Below is a simplified table & dataset to illustrate a problem I'm experiencing with a more complex one.
Code Block
create table #test( recno smallint PRIMARY KEY, value decimal (18,2))
insert into #test values (1, 3.57) insert into #test values (2, 5.32) insert into #test values (3,6.29) insert into #test values (4, 9.25) insert into #test values (5, 0.84)
Method 1: I tried inserting rows from #test into a temp table (#table) as follows
Code Block
declare @n as nvarchar(3) set @n = 1 while @n <= (select count(recno) from #test) begin exec (' insert into ##table select *, originalrecno = (select recno from #test where recno = '+@n+') from #test' ) set @n = @n + 1 end However, this yields an error message:
Code Block
Server: Msg 208, Level 16, State 1, Line 2 Invalid object name '##table'. Note - you can comment out the insert into ##table line above to view the results that I'm trying to put into ##table.
Method 2: next I tried explicitly creating ##table & rerunning the loop containing the insert
declare @n as nvarchar(3) set @n = 1 while @n <= (select count(recno) from #test) begin exec (' insert into ##table select *, originalrecno = (select recno from #test where recno = '+@n+') from #test' ) set @n = @n + 1 end This worked - it inserted the data from the select statements in the loop into ##table.
I writing a unit test which has one stored proc calling data from another stored proc. Each time I run dbo.ut_wbTestxxxxReturns_EntityTest I get a severe uncatchable error...most common cause is a trigger error. I have checked and rechecked the columns in both of the temp tables created. Any ideas as to why the error is occurring?
--Table being called.
ALTER PROCEDURE dbo.wbGetxxxxxUserReturns
@nxxxxtyId smallint,
@sxxxxxxxxUser varchar(32),
@sxxxxName varchar(32)
AS
SET NOCOUNT ON
CREATE TABLE #Scorecard_Returns
( NAME_COL varchar(64), ACCT_ID int,
ACCT_NUMBER varchar(10),
ENTITY_ID smallint,
NAME varchar(100),
ID int,
NUM_ACCOUNT int,
A_OFFICER varchar(30),
I_OFFICER varchar(30),
B_CODE varchar(30),
I_OBJ varchar(03),
LAST_MONTH real,
LAST_3MONTHS real,
IS int
)
ALTER PROCEDURE dbo.ut_wbTestxxxxReturns_EntityTest
Gurus, I have two list boxes, user can move items back n forth, from second listbox I am inserting values into a table. So far everything is working fine. Now I want to delete all the existing values from the table before inserting evertime..Please help me in this I dont know what to do. thanks kalloo
I'm trying to checking my production table table_a against a working table table_b (which i'm downlading data to)Here are the collumns i have in table_a and table_bDescription | FundID (this is not my PK) | Money I'm running an update if there is already vaule in the money collumn. I check to see if table_a matches table_b...if not i update table a with table b's value where FundID match up.What i'm having trouble on is if there is no record in table_a but there is a record in table_b. How can I insert that record into table_a? I would like to do all of this (the update and insert statement in one stored proc. if possible. )If anyone has this answer please let me know.Thanks,RB
I have created a table Table with name as Varchar and id as int. Now i have started inserting the rows like, insert into Table values ('arun',20).Yes i have inserted a row in the table. Now i have got the values " arun's ", 50. insert into Table values('arun's',20) My sqlserver is giving me an error instead of inserting the row. How will you solve this problem?
The SP UserPersist_GetByCriteria does a "SELECT * FROM tbl_User WHERE gender = @Gender AND culture = @Culture", so why am I receiving this error when both tables have the same structure?
The error is being reported as coming from UserPersist_GetByCriteria on the "SELECT * FROM tbl_User" line.
I have created a temporary table that has an identity and default values that it creates and sets but also it needs to get values from a sub query for the final insert into the temp table. I have my create temp table, and my insert into set up but my select is confusing me since some of the values I need to select are determined as they are entered into the temp table. Is there a way to alias them or not put them in the select? If I leave them out it says there are more values in the insert than in the select.
Create Table #TempLabTestConfigImport
(temp_id int identity(1,1),system_id int default 2250, labtestkey nvarchar(10) null,
INSERT INTO #tmpTable (eventName) values ('Another One')
DROP TABLE #tmpTable
this causes a null insert issue
(0 row(s) affected)
Msg 515, Level 16, State 2, Line 7
Cannot insert the value NULL into column 'statuspid', table 'tempdb.dbo.#tmpTable___________________________________________________________________________________________________________000000000130'; column does not allow nulls. INSERT fails.
The statement has been terminated.
So how do I allow the null, as the not null is coming from the ES table. But I want to allow the insert to happen without having to create the table first, this code works in SQL 2000 but fails in 2005, inserting all fileds into the insert also has it's own issues as some of the fields are delibertly left blank so in some circumstances the data returned to a grid displays correctly.
This method has been used in quite a lot of stored procedures and will be a nightmare to correct if each has to be edited.
One example of the use of is to return a dataset and then add a row at the bottom which is a sum of all the rows.
In my script component for "Opening Balance", I set my output columns like this:
Row.AccountNumber = CDate(rowValues(1)
Row.OpeningBalance = CDec(rowValues(2))
Row.ClosingBalance = Nothing
Because I don't have a value for ClosingBalance in this row, I set ClosingBalance = Nothing.
And for "Closing Balance", I set my output columns like this, because there's no value for OpeningBalance.
Row.AccountNumber = CDate(rowValues(1)
Row.OpeningBalance = Nothing
Row.ClosingBalance = Nothing
Then, in my column mappings I map OpeningBalance = OpeningBalance and ClosingBalance = ClosingBalance.
The idea being that if there's no value, then it should be set to NULL. However, in my table, I see that instead of NULLs, there's 0.00000. Which is not what I want to see.
I have a temp table that looks like this (as a result of two seperate inserts into it):
RowNumber starttime endtime ----------- ----------- ----------- 1 l 0 l NULL 2 l 360 l NULL 3 l 720 l NULL 4 l 1020 l NULL 5 l 1380 l NULL 6 l NULL l 180 7 l NULL l 540 8 l NULL l 900 9 l NULL l 1200 10 l NULL l 1440
I need some help getting it to look like this (with No NULL cell values)!
RowNumber starttime endtime ----------- ----------- ----------- 1 l 0 l 180 2 l 360 l 540 3 l 720 l 900 4 l 1020 l 1200 5 l 1380 l 1440
PLEASE help I have been looking at this for the past 3 days and can't figure it out! :o
This one is interesting...Is there any way to pass a joined parameter into a UDF as I'm attempting below?I have a temp table that I'm trying to create:create table #t3(bmkPerson int primary key,LangCode nchar(5),SName varchar(1000))insert into #t3select t2.bmkPerson, t2.LangCode,select SName from SName_trans_udf(t2.LangCode)from #t2 t2Thanks in advance,RenaeJoin Bytes!
I have to select several field values from a table and need to assign them to different variables in my SP.Here's what I do now: declare @ReceiverEmail nvarchar(50) SET @ReceiverEmail=(SELECT Email FROM Users WHERE UserCode=@UserCodeOwner) declare @UsernameSender nvarchar(50) SET @UsernameSender=(SELECT Username FROM Users WHERE UserCode=@UserCodeOwner)As you can see I have to search the Users table twice: once for the Email and a second time for the Username...and all that based on the SAME usercode...:SSo, is there an option where I only have to search the table once and return the Email and UserName fields and assign them to my variables (without using a temp table....)?
I have a pivot transform that pivots a batch type. After the pivot, each batch type has its own row with null values for the other batch types that were pivoted. I want to group two fields and max() the remaining batch types so that the multiple rows are displayed on one row. I tried using the aggregate transform, but since the batch type field is a string, the max() function fails in the package. Is there another transform or can I use the aggragate transform another way so that the max() will work on a string?
Hi, I am using a SQL back end to dynamically populate an asp.net report/page. As the data I'm interrogating is created from a tree control, I'm having to use a recursive function to retrieve the data into a series of ID values. This all happens at the moment in a DataTable manipulated with c# code. So my ID values end up in this datatable. My problem is that I am then performing a crosstab query in SQL Server 2000 and these ID are required as part of that query. Should I create a temp table and join this into the query or should i feed in a series of ID values into a where clause? Any help gratefully appreciated. Thanks. John
I would like to know if the following sql can be used to obtain specific columns from calling a stored procedure with parameters:
/* Create TempTable */ CREATE TABLE #tempTable (MyDate SMALLDATETIME, IntValue INT) GO /* Run SP and Insert Value in TempTable */ INSERT INTO #tempTable (MyDate, IntValue) EXEC TestSP @parm1, @parm2
If the above does not work or there is a better way to accomplish this goal, how to change the sql?