Using a temporary table on SRSS report - sql-server

I have a stored procedure which works without a problem at the sql server side. However, when I feed a SRSS report with this stored procedure, I am having an error such as; Invalid object name '##tempTable'.
Here is my stored procedure;
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
-- Add the parameters for the stored procedure here
#StoreId int,
#StartDate date,
#EndDate date
AS
BEGIN
DECLARE #QUERY nvarchar(MAX);
SET #QUERY = N'SELECT * INTO ##tempTable ' +
N'FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' + CONVERT(varchar(10),#StoreId) + ',' + '''' + QUOTENAME(CONVERT(varchar,#StartDate,112),'''') + '''' + ',' + '''' + QUOTENAME(CONVERT(varchar,#EndDate,112) + '''','''') + ')';
EXEC sp_executesql #QUERY;
SET NOCOUNT ON;
SELECT * FROM ##tempTable
drop table ##tempTable
END
GO
How can I solve this issue? Thanks.

A Table referenced in a Dynamic statement can only be referenced inside that dynamic statement. Take this simple query:
EXEC sp_executesql N'SELECT 1 AS I INTO #temp;';
SELECT *
FROM #temp;
Notice the statement fails with:
Msg 208, Level 16, State 0, Line 3
Invalid object name '#temp'.
It seems, however, you don't need to temporary table, and this will work fine:
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
-- Add the parameters for the stored procedure here
#StoreId int,
#StartDate date,
#EndDate date
AS
BEGIN
DECLARE #QUERY nvarchar(MAX);
SET #QUERY = N'SELECT * ' +
N'FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' + CONVERT(varchar(10),#StoreId) + ',' + '''' + QUOTENAME(CONVERT(varchar(8),#StartDate,112),'''') + '''' + ',' + '''' + QUOTENAME(CONVERT(varchar(8),#EndDate,112) + '''','''') + ')';
EXEC sp_executesql #QUERY;
END;

Try doing this
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
-- Add the parameters for the stored procedure here
#StoreId int,
#StartDate date,
#EndDate date
AS
BEGIN
DECLARE #QUERY nvarchar(MAX);
SET #QUERY = N'SELECT * INTO ##temp_global ' +
N'FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' + CONVERT(varchar(10),#StoreId) + ',' + '''' + QUOTENAME(CONVERT(varchar,#StartDate,112),'''') '''' + ',' + '''' + QUOTENAME(CONVERT(varchar,#EndDate,112) + '''','''') + ')';
EXECUTE (#QUERY)
SELECT * FROM ##temp_global
DROP TABLE ##temp_global
END

I think I had this once and I had to create the temp table initially with the column names specified and then insert into it, so that your dataset would be able to pick up the column names. So something like this may work:
ALTER PROCEDURE [dbo].[Link_SP_Inventory]
-- Add the parameters for the stored procedure here
#StoreId int,
#StartDate date,
#EndDate date
AS
BEGIN
DECLARE #QUERY nvarchar(MAX);
CREATE TABLE ##tempTable ([ColumnOne] VARCHAR(10), [ColumnTwo] DATETIME) --Add required columns here
SET #QUERY = N'SELECT * FROM OPENQUERY("172.11.111.11", N''EXEC [DB].dbo.SP_inventory ' + CONVERT(varchar(10),#StoreId) + ',' + '''' + QUOTENAME(CONVERT(varchar,#StartDate,112),'''') + '''' + ',' + '''' + QUOTENAME(CONVERT(varchar,#EndDate,112) + '''','''') + ')';
INSERT INTO ##tempTable ([ColumnOne],[ColumnTwo])
EXEC (#QUERY);
SET NOCOUNT ON;
SELECT * FROM ##tempTable
DROP TABLE ##tempTable
END
GO

Related

Turn on and off the IDENTITY_INSERT before and after insert dynamically

select
row_number() over (order by 1) as rn, *
into
#execute_insert
from
#finaldata
where
noofrows > 0;
declare #intmin int, #intmax int
select #intmin = min(rn), max(rn)
from #execute_insert
begin
declare #query nvarchar(max) ='';
select #query = concat('ALTER TABLE ' + table_Name + 'NOCHECK CONSTRAINT All ')
If set Identity_Insert ON
select #query = 'insert Into' + #Table_Name + ' '+ #column_Name
+' select ' + #Column_Name
+' from '+#Table_Name+' '+ sql_query+''
Else Identity_insert Off
end
It is not possible to toggle your Identity_Insert in SQL. However you may achieve the same by using dynamic sql. Everytime when you are inserting some data in a table, set Identity_Insert ON for that table and close it after executing your query.
You can make both ON and OFF in one command, to make sure that it is always in closed state after execution of query.
.
.
.
-- your code
SET #query = 'SET IDENTITY_INSERT ' + #Table_Name + ' ON '
SET #query = #query + ' insert Into' + #Table_Name + ' '+ #column_Name
+' select ' + #Column_Name
+' from '+#Table_Name+' '+ sql_query+''
SET #query = #query + ' SET IDENTITY_INSERT ' + #Table_Name + ' OFF '
EXEC (#query )
.
.
.
Note: I am not checking your query, hope that works fine individually, this is example to set IDENTITY_INSERT ON and OFF in single query statement.

SQL Server procedure with parameters for table name, field name, and ID of the record

I am trying this in SQL Server and it throws an error:
ALTER PROCEDURE [dbo].[GET_TEXT_DETAIL]
#id UNIQUEIDENTIFIER,
#table VARCHAR(255),
#field VARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql VARCHAR(200)
SET #sql = 'select ' + QUOTENAME(#field) + ' from ' + QUOTENAME(#table) + ' where ID = ' + QUOTENAME(#id)
EXEC (#sql)
END
I get this error:
Msg 207, Level 16, State 1, Line 1
Invalid column name 'CFC2776A-6EE1-E511-A172-005056A218B0'.
Is there any way to do this so I don't have to make a bunch or procedures to pull text from a bunch of different tables?
QUOTENAME has optional second parameter quote char, so you were close and this could be solved by:
... QUOTENAME(#id, '''')
but the most proper way for this case is passing the parameter:
set #cmd = '
SELECT t.' + QUOTENAME(#field) + '
FROM ' + QUOTENAME(#table) + ' t
WHERE t.ID = #ID'
exec sp_executesql #cmd, N'#ID uniqueidentifier', #ID
And server will be able to reuse plan as #srutzsky mentioned. Because #ID is no longer part of a query text and #cmd text remains the same for different #ID (and same #table+#field).
ALTER PROCEDURE [dbo].[GET_TEXT_DETAIL]
(
#id UNIQUEIDENTIFIER,
#table SYSNAME,
#field SYSNAME
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL NVARCHAR(MAX)
SET #SQL = '
SELECT ' + QUOTENAME(#field) + '
FROM ' + QUOTENAME(#table) + '
WHERE ID = ''' + CAST(#id AS VARCHAR(36)) + ''''
--PRINT #SQL
EXEC sys.sp_executesql #SQL
END

Pass a DataTime parameter to stored procedure and check a condition

assumption:
I need to sync a 'PublicDB' from a 'PrivateDB' database. Where two parameters should pass to stored procedure, server name and a datetime type parameter.
HistoryDate is not primary key but use for updating.
Scenario:
If today is 8th and user do not select any previous date from dateTimePicker -UI- this stored procedure only will update records on 8th.
If today is 8th and user select 5th of month= targetdate in my SP, it should delete 'PublicDB' table from 4th then insert 5th, 6th and 8th again.
Problem:
server parameter works fine but for datatime parameter:
If Sp execute in sql server get this error:
Conversion failed when converting date and/or time from character string.
if added to table Adapter it got this error:
Generated SELECT statement
Conversation failed when converting date / or time from character string.
*To apply these settings to your query click finish*
here is the sp:
CREATE PROCEDURE [dbo].[spname] #Server SYSNAME,
#TDate NVARCHAR(50) --have tested: DateTime
AS
BEGIN
DECLARE #SQL1 NVARCHAR(2000);
DECLARE #SQL2 NVARCHAR(2000);
DECLARE #LastRecordDate DATETIME;
DECLARE #Count INT;
DECLARE #TargetDate DATETIME;
SET #TargetDate = CONVERT(DATETIME, #TDate, 121);
SET #Count = CONVERT(INT, 'SELECT COUNT(*) FROM [' + #Server + '].[PublicDB].[dbo].[TableName]
WHERE HistoryDate >= [' + #TargetDate + '] ');
EXECUTE sp_executesql #Count;
IF #Count > 0 BEGIN
SET #SQL1 = 'DELETE FROM [' + #Server + '].[PublicDB].[dbo].[TableName]
WHERE HistoryDate >= [' + #TargetDate + ']
INSERT INTO [PublicDB].[dbo].[TableName]
SELECT TOP 5
[HistoryDate]
,[columnName1]
,[columnName2]
,[columnName3]
,[columnName4]
,[columnName5]
,[columnName6]
FROM PrivateDB.dbo.TableName
WHERE HistoryDate >= [' + #TargetDate + ']
';
EXECUTE sp_executesql #SQL1;
END
ELSE BEGIN
SET #LastRecordDate = CONVERT(DATETIME, 'SELECT TOP 1 HistoryDate FROM [PublicDB].[dbo].[TableName] ORDER BY HistoryDate DESC', 121);
-- has tested: cast('SELECT TOP 1 HistoryDate FROM [Public].[dbo].[TableName] ORDER BY HistoryDate DESC' as datetime)
EXECUTE sp_executesql #LastRecordDate;
SET #SQL2 = '
INSERT INTO [' + #Server + '].[PublicDB].[dbo].[TableName]
SELECT TOP 5
[HistoryDate]
,[columnName1]
,[columnName2]
,[columnName3]
,[columnName4]
,[columnName5]
,[columnName6]
FROM PrivateDB.dbo.TableName
WHERE HistoryDate > [' + #LastRecordDate + ']
';
EXECUTE sp_executesql #SQL2;
END
END
I think these lines could be the problem
SET #Count = CONVERT(INT, 'SELECT COUNT(*) FROM [' + #Server + '].[PublicDB].[dbo].[TableName]
WHERE HistoryDate >= [' + #TargetDate + '] ');
You are asking to convert a string / datetime to an int
I guess that you are trying to get a count from the select statement, one way would be something like the following (not tested!)
CREATE TABLE #t_count(no int)
DECLARE #sqlcount varchar(1000)
DECLARE #count int
SET #sqlcount = 'INSERT into #t_count SELECT COUNT(*)
FROM [' + #Server + '].[PublicDB].[dbo].[TableName]
WHERE HistoryDate >=''' + convert(varchar(30),#TargetDate,120) + ''''
EXEC( #sqlcount )
SELECT #count = no FROM #t_count
example sqlfiddle
EDIT
I see you updated your answer a little http://sqlfiddle.com/#!2/d41d8/14528
but if you read the answer above, you will see that it
creates a temp table
CREATE TABLE #t_count(no int)
builds an sql string to insert the count into the temp table
SET #sqlcount = 'INSERT into #t_count SELECT COUNT(*)
FROM [' + #Server + '].[PublicDB].[dbo].[TableName]
WHERE HistoryDate >=''' + convert(varchar(30),#TargetDate,120) + ''''
EXEC( #sqlcount )
gets the count value from the table
SELECT #count = no FROM #t_count
Your edit does not do this!
Also you are enclosing literal values in [] for some reason these need removed
good
where historydate = '2012-12-12 12:12'
bad
where historydate = [2012-12-12 12:12]

Insert script for a particular set of rows in SQL

I am using SQL Server 2008. I use to take the script of my data from SQL table using Tasks --> Generate Scripts option.
Here is my problem:
Let's say I have 21,000 records in Employee table. When I take the script of this table, it takes the insert script for all 21000 records. What is the solution if I want to take only the script of 18000 records from the table?
Is there any solution using SQL query or from the tasks wizard?
Thanks in advance...
Create a new View where you select your desired rows from your Employee table e.g. SELECT TOP 21000...
Then simply script that View instead of the Table.
In case the views are not an option for you I wrote the following code based on the Aaron Bertrand's answer here that will give the insert statement for a single record in the db.
CREATE PROCEDURE dbo.GenerateSingleInsert
#table NVARCHAR(511), -- expects schema.table notation
#pk_column SYSNAME, -- column that is primary key
#pk_value NVARCHAR(10) -- change data type accordingly
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cols NVARCHAR(MAX), #vals NVARCHAR(MAX),
#valOut NVARCHAR(MAX), #valSQL NVARCHAR(MAX);
SELECT #cols = N'', #vals = N'';
SELECT #cols = #cols + ',' + QUOTENAME(name),
#vals = #vals + ' + '','' + ' + 'ISNULL('+REPLICATE(CHAR(39),4)+'+RTRIM(' +
CASE WHEN system_type_id IN (40,41,42,43,58,61) -- dateteime and time stamp type
THEN
'CONVERT(CHAR(8), ' + QUOTENAME(name) + ', 112) + '' ''+ CONVERT(CHAR(14), ' + QUOTENAME(name) + ', 14)'
WHEN system_type_id IN (35) -- text type
THEN
'REPLACE(CAST(' + QUOTENAME(name) + 'as nvarchar(MAX)),'+REPLICATE(CHAR(39),4)+','+REPLICATE(CHAR(39),6)+')'
ELSE
'REPLACE(' + QUOTENAME(name) + ','+REPLICATE(CHAR(39),4)+','+REPLICATE(CHAR(39),6)+')'
END
+ ')+' + REPLICATE(CHAR(39),4) + ',''null'') + '
FROM sys.columns WHERE [object_id] = OBJECT_ID(#table)
AND system_type_id <> 189 -- can't insert rowversion
AND is_computed = 0; -- can't insert computed columns
SELECT #cols = STUFF(#cols, 1, 1, ''),
#vals = REPLICATE(CHAR(39),2) + STUFF(#vals, 1, 6, '') + REPLICATE(CHAR(39),2) ;
SELECT #valSQL = N'SELECT #valOut = ' + #vals + ' FROM ' + #table + ' WHERE '
+ QUOTENAME(#pk_column) + ' = ''' + RTRIM(#pk_value) + ''';';
EXEC sp_executesql #valSQL, N'#valOut NVARCHAR(MAX) OUTPUT', #valOut OUTPUT;
SELECT SQL = 'INSERT ' + #table + '(' + #cols + ') SELECT ' + #valOut;
END
I took the above code and wrapped it the following proc that will use the where clause you give it to select which insert statements to create
CREATE PROCEDURE dbo.GenerateInserts
#table NVARCHAR(511), -- expects schema.table notation
#pk_column SYSNAME, -- column that is primary key
#whereClause NVARCHAR(500) -- the where clause used to parse down the data
AS
BEGIN
declare #temp TABLE ( keyValue nvarchar(10), Pos int );
declare #result TABLE ( insertString nvarchar(MAX) );
declare #query NVARCHAR(MAX)
set #query =
'with qry as
(
SELECT ' + #pk_column + ' as KeyValue, ROW_NUMBER() over(ORDER BY ' + #pk_column + ') Pos
from ' + #table + '
' + #whereClause + '
)
select * from qry'
insert into #temp
exec sp_sqlexec #query
Declare #i int, #key nvarchar(10)
select #i = count(*) from #temp
WHILE #i > 0 BEGIN
select #key = KeyValue from #temp where Pos = #i
insert into #result
exec [dbo].[GenerateSingleInsert] #table, #pk_column, #key
set #i = #i - 1
END
select insertString from #result
END
Calling it could look like the following. You pass in the table name, the table primary key and the where clause and you should end up with your insert statements.
set #whereClause = 'where PrettyColorsId > 1000 and PrettyColorsID < 5000'
exec [dbo].GenerateInserts 'dbo.PrettyColors', 'PrettyColorsID', #whereClause
set #whereClause = 'where Color in (' + #SomeValues + ')'
exec [dbo].GenerateInserts 'dbo.PrettyColors', 'PrettyColorsID', #whereClause

How to create a UDF or View in another database that references the correct sys.objects table in the caller?

Using SQL Server 2008, I'd like to create a UDF that gives me the create date of an object. This is the code:
create function dbo.GetObjCreateDate(#objName sysname) returns datetime as
begin
declare #result datetime
select #result = create_date from sys.objects where name = #objname
return #result
end
go
I'd like to put this UDF in the master database or some other shared database so that it is accessible from anywhere, except that if I do that then the sys.objects reference pulls from the master database instead of the database that I'm initiating my query from. I know you can do this as the information_schema views sit in master and just wrap calls to local instances of sys.objects, so I'm hoping there's a simple way to do that with my UDF as well.
Try this:
CREATE FUNCTION dbo.GetObjCreateDate(#objName sysname, #dbName sysname)
RETURNS datetime AS
BEGIN
DECLARE #createDate datetime;
DECLARE #params nvarchar(50);
DECLARE #sql nvarchar(500);
SET #params = '#createDate datetime OUTPUT';
SELECT #sql = 'SELECT #createDate = create_date FROM ' + #dbName + '.sys.objects WHERE name = ''' + #objname + '''';
EXEC sp_executesql #sql, #params, #createDate = #createDate OUTPUT;
RETURN #createDate
END
;
Why not do this instead?
Create a stored procedure that creates a view in the master database containing all of the information in sys.objects from each database on the server.
Create a DDL Trigger that gets fired whenever a CREATE, ALTER or DROP statement is executed for a database. The trigger would then execute the stored procedure in step #1. This allows the view to be automatically updated.
(Optional) Create a user defined function that queries the view for the creation date of a given object.
Stored Procedure DDL:
USE [master];
GO
CREATE PROCEDURE dbo.BuildAllServerObjectsView
AS
SET NOCOUNT ON;
IF OBJECT_ID('master.dbo.AllServerObjects') IS NOT NULL
EXEC master..sp_SQLExec 'DROP VIEW dbo.AllServerObjects;';
IF OBJECT_ID('tempdb..Databases') IS NOT NULL
DROP TABLE #Databases;
DECLARE #CreateView varchar(8000);
SET #CreateView = 'CREATE VIEW dbo.AllServerObjects AS' + CHAR(13)+CHAR(10) + CHAR(13)+CHAR(10);
SELECT name COLLATE SQL_Latin1_General_CP1_CI_AS AS 'name'
INTO #Databases
FROM sys.databases
ORDER BY name;
DECLARE #DatabaseName nvarchar(100);
WHILE (SELECT COUNT(*) FROM #Databases) > 0
BEGIN
SET #DatabaseName = (SELECT TOP 1 name FROM #Databases ORDER BY name);
SET #CreateView +='SELECT N'+QUOTENAME(#DatabaseName, '''')+' AS ''database_name''' + CHAR(13)+CHAR(10)
+ ' ,name COLLATE SQL_Latin1_General_CP1_CI_AS AS ''object_name''' + CHAR(13)+CHAR(10)
+ ' ,object_id' + CHAR(13)+CHAR(10)
+ ' ,principal_id' + CHAR(13)+CHAR(10)
+ ' ,schema_id' + CHAR(13)+CHAR(10)
+ ' ,parent_object_id' + CHAR(13)+CHAR(10)
+ ' ,type' + CHAR(13)+CHAR(10)
+ ' ,type_desc' + CHAR(13)+CHAR(10)
+ ' ,create_date' + CHAR(13)+CHAR(10)
+ ' ,modify_date' + CHAR(13)+CHAR(10)
+ ' ,is_ms_shipped' + CHAR(13)+CHAR(10)
+ ' ,is_published' + CHAR(13)+CHAR(10)
+ ' ,is_schema_published' + CHAR(13)+CHAR(10)
+ ' FROM ' + QUOTENAME(#DatabaseName) + '.sys.objects';
IF (SELECT COUNT(*) FROM #Databases) > 1
SET #CreateView += CHAR(13)+CHAR(10) + CHAR(13)+CHAR(10) + ' UNION' + CHAR(13)+CHAR(10);
ELSE
SET #CreateView += ';';
DELETE #Databases
WHERE name = #DatabaseName;
END;
--PRINT #CreateView --<== Uncomment this to see the DDL for the view.
EXEC master..sp_SQLExec #CreateView;
IF OBJECT_ID('tempdb..Databases') IS NOT NULL
DROP TABLE #Databases;
GO
Function DDL:
USE [master];
GO
CREATE FUNCTION dbo.GetObjCreateDate(#DatabaseName sysname, #objName sysname) RETURNS DATETIME AS
BEGIN
DECLARE #result datetime;
SELECT #result = create_date
FROM master.dbo.AllServerObjects
WHERE [database_name] = #DatabaseName
AND [object_name] = #objname;
RETURN #result;
END
GO
Sample Usage:
SELECT master.dbo.GetObjCreateDate('MyDatabase', 'SomeObject') AS 'Created';
SELECT master.dbo.GetObjCreateDate(DB_NAME(), 'spt_monitor') AS 'Created';
Does it have to be a function? If you just want it accessible everywhere, a trick is to put your code in a varchar and sp_executesql it:
create procedure dbo.GetObjCreateDate(#objName sysname)
as
declare #sql nvarchar(max)
select #sql = 'select create_date from sys.objects where name = ''' + #objname + ''''
EXEC sp_executesql #sql
go
There seems to be an undocumented stored procedure that allows you to create your own system objects: sp_ms_marksystemobject
You can read more on http://www.mssqltips.com/tip.asp?tip=1612
Have a look at How to Write Your Own System Functions. I believe that it may help you

Resources