Copy from one temp table to another temp table on condition base? - sql

How to copy from one temp table to another temp table on condition base then how to retrieve from that pasted table?
I tried like below but retrieving from both conditions where as I want pasted table data selection which I never getting.
alter procedure Get_LoginLogutDetails
as
begin
DECLARE #cmd AS NVARCHAR(max)
DECLARE #cmdOriginal AS NVARCHAR(max)
CREATE TABLE #result
(
LoggedOutTime datetime
)
CREATE TABLE #OriginalResult
(
Duration varchar(100)
)
declare #loggedOutTime varchar(20)
SET #cmd ='select LoggedOutTime from LastLoggedInDetails'
Insert into #result
EXEC(#cmd)
declare result_cursor cursor for
SELECT LoggedOutTime
from #result
where LoggedOutTime is null
OPEN result_cursor
FETCH NEXT FROM result_cursor INTO #loggedOutTime
WHILE ##FETCH_STATUS = 0
BEGIN
if(#loggedOutTime is null)
begin
select 'Running..'
Insert into #OriginalResult
EXEC(#cmd)
end
else if(#loggedOutTime is not null)
begin
select LoggedOutTime from #result
Insert into #OriginalResult
EXEC(#cmd)
end
FETCH NEXT FROM result_cursor INTO #loggedOutTime
END
select * from #OriginalResult
end

Ok, so i had a read through your script and have tried to work out what you are trying to do. it looks like you are possibly trying to get the LoggedOutTimes when there is a time, if there is no logged out time, you want the result "Running..." to be inserted into a temp table.
SELECT ISNULL(LoggedOutTime, 'Running...')
INTO #OriginalResult
FROM LastLoggedInDetails
This gives you a temp table with the above scenario. Unsure on the datatype of LoggedOutTime, you may need to convert it to an nvarchar.
Your original question doesn't make a lot of sense, you should try rewording it to get some more accurate help.

Sorry to all for my not good explainations , but I finally reached my need.
I want like nelow.
select LastLoggedInDetails.LoggedInTime,case
when LastLoggedInDetails.LoggedOutTime is not null then CONVERT(VARCHAR(100),DATEDIFF (hour,LastLoggedInDetails.LoggedInTime ,LastLoggedInDetails.LoggedOutTime ))+' Hours '+
CONVERT(VARCHAR(100),DATEDIFF (minute,LastLoggedInDetails.LoggedInTime ,LastLoggedInDetails.LoggedOutTime )%60) +' Minutes'
when LastLoggedInDetails.LoggedOutTime is null then 'Running...'
end
from dbo.LastLoggedInDetails

Related

looping through recordset in stored procedure

I have created a tbl having SELECT statement as value (fieldname sqltxt).
Now want to read rows one by one and execute all the select statement stored in this table.
If it does not return any row i.e. zero row
insert a new record in DMSResults with value of DOCID from DMSRec
For that I use following script
set nocount on
use TESTDB
declare #sqlTXT as varchar(max);
DECLARE #DocID nvarchar(30);
drop table DMSResults
CREATE TABLE DMSResults (DOCID nvarchar(30) );`
drop table DMSRec
SELECT .....intoDMSRec FROM tbl....
Above syntax is a Big SQl script to create a recordset.
For my conveyance I insert all the records into new tbl.
Its returns more than 10,00,000 records
Now want to loop in tbl DMSREC, read the value of field sqltxt
Execute that statement.
If it doesn't return a record
Insert a record in DMSResults with value of DOCID field.
I also tried with following commands, but do not know how to loop in sql for next rec until eof and exit
Since DMSRec is a temporary table, once a row is processed then we can remove record from DMSRec.
declare #rc as bigint
Select #rc = Row_Count
From sys.dm_db_partition_stats
Where Object_Name(Object_Id) = 'DMSRec'
WHILE #rc <1
BEGIN
exec(select sqltxt from dmsrec where row=1)
-- here check record is exist or not then
-- if it is not exist or returning zero
-- add record in dmsresult with docid value
-- delete dmsrec where row=1
-- loop for next
END
Considering the huge size of database SQL-Server 2008r2 please guide me any optimize solution.
DMSRec TBL recordset.
DOCID         SQLTXT
A01/17-18     SELECT VRNO FROM TBL_LET WHERE VRNO='A01/17-18'
I can't address the actual problem here, but I can elaborate on the question of how to loop through all records. BTW< loops are terrible for performance and thus are avoided at all costs in SQL Server.
--get the row count of the table
declare #rc as bigint
Select #rc = (select count(*) from DMSRec)
--variables for incrementing rows and storing SQL
declare #i bigint = 1
declare #sql varchar(max)
WHILE #i <= #rc
BEGIN
--get the SQL Statement from the table
set #sql = (select sqltxt from dmsrec where row=#i)
--If no value was returned, insert into DSMResults
if (#sql is null) or (ltrim(rtrim(#sql)) = '')
begin
insert into DMSResults
select DOCID from dmsrec
end
--If a value was returned, execute that statement
else
begin
exec(#sql)
end
--increment the row number
set #i = #i + 1
END

How to insert result of Stored Procedure into Temp Table without declaring Temp Table Columns

I want to insert the values of stored procedure into a temp table without predefining the columns for the temp table.
Insert Into #Temp1 Exec dbo.sp_GetAllData #Name = 'Jason'.
How can I do this ? I saw an option as below but can I do it without mentioning the server name ?
SELECT * INTO #TestTableT FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;',
'EXEC tempdb.dbo.GetDBNames')
-- Select Table
SELECT *
FROM #TestTableT;
I could not find a possible solution without defining temp table schema and writing server name. So, I changed the code and the queries to handle with only known schema. Code example is as below
CREATE TABLE #TestTable ([name] NVARCHAR(256), [database_ID] INT);
INSERT INTO #TestTable
EXEC GetDBNames
SELECT * FROM #TestTable;
As provided in the link https://blog.sqlauthority.com/2013/05/27/sql-server-how-to-insert-data-from-stored-procedure-to-table-2-different-methods/
No-one said it had to be pretty:
CREATE PROCEDURE p AS
SELECT 1 as x, 2 as y, 3 as z
GO
DECLARE c CURSOR FOR
SELECT
name, system_type_name
FROM sys.dm_exec_describe_first_result_set_for_object(OBJECT_ID('p'), 0);
DECLARE #name sysname, #type sysname;
CREATE TABLE #t(fake int)
OPEN c
FETCH NEXT from c into #name, #type
WHILE (##FETCH_STATUS = 0)
BEGIN
EXEC ('ALTER TABLE #t ADD ' + #name + ' ' + #type)
FETCH NEXT from c into #name, #type
END
CLOSE C
DEALLOCATE c
ALTER TABLE #t DROP COLUMN fake;
INSERT INTO #t EXEC p;
GO

If condition not working inside dynamic sql

In below dynamic sql I am trying to check whether temporary table (#Table) already exists if not then create using some other table.
But my problem is that irrespective what is the value in IF condtion, I am always getting error for select statement which is inside If condition
There is already an object named '#Table' in the database.
Below is the sql code.
declare #sqlstring varchar(max)
set #sqlstring=N'
select * into #Table from mst_country
if(object_id(''tempdb..#Table'') is null)
begin
select * into #Table from mst_country_bkp
end'
exec(#sqlstring)
Can any one please let us know why it can be happening?
You need to drop the temp table once you are done with your query like this:
declare #sqlstring varchar(max)
set #sqlstring=N'
IF OBJECT_ID(''tempdb.dbo.#Table'', ''U'') IS NOT NULL
DROP TABLE #Table;
select * into #Table from mst_country
if(object_id(''tempdb..#Table'') is null)
begin
select * into #Table from mst_country_bkp
end'
exec(#sqlstring)
EDIT:
The issue is that you cannot have two SELECT INTO inside the same sql statement. This is a leftover from SQL 6.5 which did not have deferred name resolution. Try this:
declare #sqlstring varchar(max)
set #sqlstring=N'
IF OBJECT_ID(''tempdb.dbo.#Table'', ''U'') IS NOT NULL
DROP TABLE #Table;
select * into #Table from mst_country
insert into #Table(col1,col2,....)
select col1,col2,.... from mst_country_bkp
end'
exec(#sqlstring)
When compiling the sqlserver doesn't allow you creating the same temporary table in the same scope twice. You can actually cheat the sqlserver like this, so it doesn't realize that the temporary table was already created:
declare #sqlstring varchar(max)
set #sqlstring=N'
exec(''select * into #Table from mst_country'')
if(object_id(''tempdb..#Table'') is null)
select * into #Table from mst_country_bkp
'
exec(#sqlstring)

How do I get a collection of every value in every column of a table?

I have two tables, Values and SpecialValues.
Values has two columns, RecordID and ValueName.
SpecialValues is a table which contains a single row, and thirty columns named SpecialValueName1, SpecialValueName2, SpecialValueName3, etc.
There are obvious database design problems with this system.
That aside, can someone explain to me how to query SpecialValues so that I can get a collection of all the values of every row from the table, and exclude them from a Select from Values?
There's probably some easy way to do this or create a View for it or something, but I think looking at this code might have broken me for the moment...
EDIT: I'd like a query to get all the individual values from every row and column of a given table (in this case the SpecialValues table) so that the query does not need to be updated the next time someone adds another column to the SpecialValues table.
This creates a #SpecialValuesColumns temporary table to store all the column names from SpecialValues.
It then uses a cursor to insert all the values from each of those columns into another temporary table #ProtectedValues.
It then uses a NOT IN query to exclude all of those values from a query to Values.
This code is bad and I feel bad for writing it, but it seems like the least-worst option open to me right now.
DECLARE #SpecialColumnsCount INT;
DECLARE #Counter INT;
DECLARE #CurrentColumnName VARCHAR(255);
DECLARE #ExecSQL VARCHAR(1024);
SET #Counter = 1;
CREATE TABLE #ProtectedValues(RecordID INT IDENTITY(1,1) PRIMARY KEY NOT NULL, Value VARCHAR(255));
DECLARE #SpecialValuesColumns TABLE (RecordID INT IDENTITY(1,1) PRIMARY KEY NOT NULL, ColumnName VARCHAR(255));
INSERT INTO #SpecialValuesColumns (ColumnName)
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'SpecialValues' AND
DATA_TYPE = 'varchar' AND
CHARACTER_MAXIMUM_LENGTH = 255
SELECT #SpecialColumnsCount = COUNT(*) FROM #SpecialValuesColumns
WHILE #Counter <= #SpecialColumnsCount
BEGIN
SELECT #CurrentColumnName = ColumnName FROM #SpecialValuesColumns WHERE RecordID = #Counter;
SET #ExecSQL = 'INSERT INTO #ProtectedValues (Value) SELECT ' + #CurrentColumnName + ' FROM SpecialValues'
EXEC (#ExecSQL)
SET #Counter = #Counter + 1;
END
SELECT * FROM Values WHERE ValueName NOT IN (SELECT ValueName COLLATE DATABASE_DEFAULT FROM #ProtectedValues)
DROP TABLE #ProtectedValues;
I might have misunderstood but doesn't this do it?
SELECT * FROM Values
WHERE ValueName NOT IN (
SELECT SpecialValueName1 FROM SpecialValues
UNION SELECT SpecialValueName2 FROM SpecialValues
UNION SELECT SpecialValueName3 FROM SpecialValues
etc..
)
You could of course make the subquery into a view instead.
*Edit:
This is quite ugly but should solve your problem:
First Create procedure #1
CREATE PROCEDURE [dbo].[SP1]
As
DECLARE
#Query nvarchar(MAX),
#Table nvarchar(255),
#Columns nvarchar(255)
CREATE TABLE #TempTable (Value nvarchar(255))
SET #Table = 'SpecialValues'
SELECT [COLUMN_NAME]
FROM [INFORMATION_SCHEMA].[COLUMNS]
WHERE [TABLE_NAME] = #Table
DECLARE Table_Cursor CURSOR FOR
SELECT COLUMN_NAME
FROM [INFORMATION_SCHEMA].[COLUMNS]
WHERE [TABLE_NAME] = #Table
OPEN Table_Cursor
FETCH NEXT FROM Table_Cursor INTO #Columns
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #TempTable EXEC SP2 #Columns = #Columns, #Table = #Table
FETCH NEXT FROM Table_Cursor INTO #Columns
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor
SELECT ValueName FROM Value WHERE Value NOT IN (SELECT * FROM #TempTable)
TRUNCATE TABLE #TempTable
DROP TABLE #TempTable
Then Create procedure #2
CREATE PROCEDURE [dbo].[SP2]
#Columns nvarchar(255) = '',
#Table nvarchar(255)
AS
DECLARE
#Query nvarchar(MAX)
SET #Query = 'SELECT TOP 1 CONVERT(nvarchar, ' + #Columns + ') FROM ' + #Table
EXEC (#Query)
Then lastly execute the procedure
EXEC SP1
You need to unpivot the values in specialvalues. A pretty easy way to do that is with cross apply syntax:
select sv.value
from specialvalues sv cross apply
(values(sv.SpecialValueName1), (sv.SpecialValueName2), . . .
) sv(value)
where sv.value is not null;
You can exclude these from the list using not in, not exists or a left join.
What ever way you cut it, you have to specify the columns in SpecialValues, you can do this with a long set of UNION queries, or use UNPIVOT:
select SpecialValue
from (select SpecialValueName1,SpecialValueName2,SpecialValueName3 from #SpecialValues) p
unpivot (SpecialValue FOR ROW IN (SpecialValueName1,SpecialValueName2,SpecialValueName3))
AS unpvt
You can then incorporate this into a query on Values using NOT IN
select * from [Values] where ValueName not in (
select SpecialValue
from (select SpecialValueName1,SpecialValueName2,SpecialValueName3 from #SpecialValues) p
unpivot (SpecialValue FOR ROW IN (SpecialValueName1,SpecialValueName2,SpecialValueName3))
AS unpvt
)

How to make table dynamic in sql

Does anyone know how to write a script in stored proc to run the table based on the variable (or will it possible to do so?)?
for example:
I have 3 tables name called customer, supplier, and support
when user input 1, then run table customer, 2 table supplier and 3 table support
declare #input int;
if #input =1
begin
declare #table varchar(50); set #table = 'customer'
end
if #input =2
begin
declare #table varchar(50); set #table = 'supplier '
end
if #input =3
begin
declare #table varchar(50); set #table = 'support'
end
select *
INTO ##test
from #table
IF it really is that simple, why not just repeat the Select?
if #input =1
begin
Select * INTO ##test From customer
end
if #input =2
begin
Select * INTO ##test From supplier
end
if #input =3
begin
Select * INTO ##test From support
end
yes you can do it by using dynamic sql "EXEC" or by "Sp_Executesql" command.
Example :
USE Northwind
GO
CREATE TABLE #MyTemp
( RowID int IDENTITY,
LastName varchar(20)
)
DECLARE #SQL nvarchar(250)
SET #SQL = 'INSERT INTO #MyTemp SELECT LastName FROM Employees;'
EXECUTE sp_executesql #SQL
Why do you want to do this? It seems like a bad idea at first glance.
Can you post what your stored procedure is doing and any relevant tables? I suspect that you may be able to either:
Modify your schema in such a way
that you would no longer to do
this
Create different stored procedures
to do what you want on each table instead of forcing it into one proc.
There are several issues that come up when you use dynamic SQL that you should be aware of. Here is a fairly comprehensive article on the pros and cons.