export txt file with all parameter values during the report execution - sql

I've developed one report in Report Builder 3.0 , report server being SRSS 2008 R2. This report has one report parameter named id_product. There are two data sets available. One data set is for populating the report table. In the second data set I'm trying to export the id_product. The below query works fine only for single valued parameter id_product, this query being used in the second data set Report pops-up an error when trying to run the report for multiple products at the same time. I looked in SQL Profiler and it seems like inserting the parameter values in the global temporary table is not possible using the current code.
I'm aware of the VB Expression named Join but in such case I'm not sure if I can use it. It would be great if I can use this kind of expression. This way I would not create the data set anymore.
Current query:
drop table ##SelectedValues
create table ##SelectedValues(id_product nvarchar(max))
insert into ##SelectedValues(#id_product)
exec xp_cmdshell 'bcp "select ''id_product''
union all select * from ##SelectedValues" queryout "G:\Report\sqloutput.csv" -c -T -t'
Input: ProductId parameter values : 12, 16, 20
Desired output in csv:
id_product
12
16
20

You can either use a split function that parses the comma delimited string to table rows, or you can use my favorite, dynamic sql! :)
if object_id('tempdb..#SelectedValues') is not null
drop table #SelectedValues
create table #SelectedValues(id_product nvarchar(max))
declare #id_product nvarchar(max),#sql nvarchar(max)
set #id_product = '12, 16, 20'
set #sql =
'select ''' + replace(#id_product,', ',''' union all select ''') + ''''
insert into #SelectedValues(id_product) exec(#sql)
select * from #SelectedValues

Related

Store a database name in variable & then using it dynamically

I have a Table in my Database Which have name of all the Database of my Server
Table Look like
create Table #db_name_list(Did INT IDENTITY(1,1), DNAME NVARCHAR(100))
INSERT INTO #db_name_list
SELECT 'db_One ' UNION ALL
SELECT 'db_Two' UNION ALL
SELECT 'db_Three' UNION ALL
SELECT 'db_four' UNION ALL
SELECT 'db_five'
select * from #db_name_list
I have so many SP in my Database..Which uses multiple table and Join Them..
At Present I am using the SQL code like
Select Column from db_One..Table1
Left outer join db_two..Table2
on ....some Condition ....
REQUIREMENT
But I do not want to HARDCODE the DATABASE Name ..
I want store DataBase name in Variable and use that .
Reason :: I want to restore same Database with Different name and want to Run those SP..At Present we Cant Do ,Because I have used db_One..Table1
or db_two..Table2
I want some thing like ...
/SAMPLE SP/
CREATE PROCEDURE LOAD_DATA
AS
BEGIN
DECLARE #dbname nvarchar(500)
set #dbname=( SELECT DNAME FROM #db_name_list WHERE Did=1)
set #dbname2=( SELECT DNAME FROM #db_name_list WHERE Did=2)
PRINT #DBNAME
SELECT * FROM #dbname..table1
/* or */
SELECT * FROM #dbname2.dbo.table1
END
i.e using Variable Instead of Database name ..
But it thow error
"Incorrect syntax near '.'."
P.S This was posted by some else on msdn but the answer there was not clear & I had the same kind of doubt. So please help
You can't use a variable like this in a static sql query. You have to use the variable in dynamic sql instead, in order to build the query you want to execute, like:
DECLARE #sql nvarchar(500) = 'SELECT * FROM ' + #dbname + '.dbo.mytable'
EXEC(#sql);
There seem to be a couple of options for you depending on your circumstances.
1. Simple - Generalise your procedures
Simply take out the database references in your stored procedure, as there is no need to have an explicit reference to the database if it is running against the database it is stored in. Your select queries will look like:
SELECT * from schema.table WHERE x = y
Rather than
SELECT * from database.schema.table WHERE x = y
Then just create the stored procedure in the new database and away you go. Simply connect to the new database and run the SP. This method would also allow you to promote the procedure to being a system stored procedure, which would mean they were automatically available in every database without having to run CREATE beforehand. For more details, see this article.
2. Moderate - Dynamic SQL
Change your stored procedure to take a database name as a parameter, such as this example:
CREATE PROCEDURE example (#DatabaseName VARCHAR(200))
AS
BEGIN
DECLARE #SQL VARCHAR(MAX) = 'SELECT * FROM ['+#DatabaseName+'].schema.table WHERE x = y'
EXEC (#SQL)
END

dynamic sql not working . Regular sql working [duplicate]

It looks like #temptables created using dynamic SQL via the EXECUTE string method have a different scope and can't be referenced by "fixed" SQLs in the same stored procedure.
However, I can reference a temp table created by a dynamic SQL statement in a subsequence dynamic SQL but it seems that a stored procedure does not return a query result to a calling client unless the SQL is fixed.
A simple 2 table scenario:
I have 2 tables. Let's call them Orders and Items. Order has a Primary key of OrderId and Items has a Primary Key of ItemId. Items.OrderId is the foreign key to identify the parent Order. An Order can have 1 to n Items.
I want to be able to provide a very flexible "query builder" type interface to the user to allow the user to select what Items he want to see. The filter criteria can be based on fields from the Items table and/or from the parent Order table. If an Item meets the filter condition including and condition on the parent Order if one exists, the Item should be return in the query as well as the parent Order.
Usually, I suppose, most people would construct a join between the Item table and the parent Order tables. I would like to perform 2 separate queries instead. One to return all of the qualifying Items and the other to return all of the distinct parent Orders. The reason is two fold and you may or may not agree.
The first reason is that I need to query all of the columns in the parent Order table and if I did a single query to join the Orders table to the Items table, I would be repoeating the Order information multiple times. Since there are typically a large number of items per Order, I'd like to avoid this because it would result in much more data being transfered to a fat client. Instead, as mentioned, I would like to return the two tables individually in a dataset and use the two tables within to populate a custom Order and child Items client objects. (I don't know enough about LINQ or Entity Framework yet. I build my objects by hand). The second reason I would like to return two tables instead of one is because I already have another procedure that returns all of the Items for a given OrderId along with the parent Order and I would like to use the same 2-table approach so that I could reuse the client code to populate my custom Order and Client objects from the 2 datatables returned.
What I was hoping to do was this:
Construct a dynamic SQL string on the Client which joins the orders table to the Items table and filters appropriate on each table as specified by the custom filter created on the Winform fat-client app. The SQL build on the client would have looked something like this:
TempSQL = "
INSERT INTO #ItemsToQuery
OrderId, ItemsId
FROM
Orders, Items
WHERE
Orders.OrderID = Items.OrderId AND
/* Some unpredictable Order filters go here */
AND
/* Some unpredictable Items filters go here */
"
Then, I would call a stored procedure,
CREATE PROCEDURE GetItemsAndOrders(#tempSql as text)
Execute (#tempSQL) --to create the #ItemsToQuery table
SELECT * FROM Items WHERE Items.ItemId IN (SELECT ItemId FROM #ItemsToQuery)
SELECT * FROM Orders WHERE Orders.OrderId IN (SELECT DISTINCT OrderId FROM #ItemsToQuery)
The problem with this approach is that #ItemsToQuery table, since it was created by dynamic SQL, is inaccessible from the following 2 static SQLs and if I change the static SQLs to dynamic, no results are passed back to the fat client.
3 around come to mind but I'm look for a better one:
1) The first SQL could be performed by executing the dynamically constructed SQL from the client. The results could then be passed as a table to a modified version of the above stored procedure. I am familiar with passing table data as XML. If I did this, the stored proc could then insert the data into a temporary table using a static SQL that, because it was created by dynamic SQL, could then be queried without issue. (I could also investigate into passing the new Table type param instead of XML.) However, I would like to avoid passing up potentially large lists to a stored procedure.
2) I could perform all the queries from the client.
The first would be something like this:
SELECT Items.* FROM Orders, Items WHERE Order.OrderId = Items.OrderId AND (dynamic filter)
SELECT Orders.* FROM Orders, Items WHERE Order.OrderId = Items.OrderId AND (dynamic filter)
This still provides me with the ability to reuse my client sided object-population code because the Orders and Items continue to be returned in two different tables.
I have a feeling to, that I might have some options using a Table data type within my stored proc, but that is also new to me and I would appreciate a little bit of spoon feeding on that one.
If you even scanned this far in what I wrote, I am surprised, but if so, I woul dappreciate any of your thoughts on how to accomplish this best.
You first need to create your table first then it will be available in the dynamic SQL.
This works:
CREATE TABLE #temp3 (id INT)
EXEC ('insert #temp3 values(1)')
SELECT *
FROM #temp3
This will not work:
EXEC (
'create table #temp2 (id int)
insert #temp2 values(1)'
)
SELECT *
FROM #temp2
In other words:
Create temp table
Execute proc
Select from temp table
Here is complete example:
CREATE PROC prTest2 #var VARCHAR(100)
AS
EXEC (#var)
GO
CREATE TABLE #temp (id INT)
EXEC prTest2 'insert #temp values(1)'
SELECT *
FROM #temp
1st Method - Enclose multiple statements in the same Dynamic SQL Call:
DECLARE #DynamicQuery NVARCHAR(MAX)
SET #DynamicQuery = 'Select * into #temp from (select * from tablename) alias
select * from #temp
drop table #temp'
EXEC sp_executesql #DynamicQuery
2nd Method - Use Global Temp Table:
(Careful, you need to take extra care of global variable.)
IF OBJECT_ID('tempdb..##temp2') IS NULL
BEGIN
EXEC (
'create table ##temp2 (id int)
insert ##temp2 values(1)'
)
SELECT *
FROM ##temp2
END
Don't forget to delete ##temp2 object manually once your done with it:
IF (OBJECT_ID('tempdb..##temp2') IS NOT NULL)
BEGIN
DROP Table ##temp2
END
Note: Don't use this method 2 if you don't know the full structure on database.
I had the same issue that #Muflix mentioned. When you don't know the columns being returned, or they are being generated dynamically, what I've done is create a global table with a unique id, then delete it when I'm done with it, this looks something like what's shown below:
DECLARE #DynamicSQL NVARCHAR(MAX)
DECLARE #DynamicTable VARCHAR(255) = 'DynamicTempTable_' + CONVERT(VARCHAR(36), NEWID())
DECLARE #DynamicColumns NVARCHAR(MAX)
--Get "#DynamicColumns", example: SET #DynamicColumns = '[Column1], [Column2]'
SET #DynamicSQL = 'SELECT ' + #DynamicColumns + ' INTO [##' + #DynamicTable + ']' +
' FROM [dbo].[TableXYZ]'
EXEC sp_executesql #DynamicSQL
SET #DynamicSQL = 'IF OBJECT_ID(''tempdb..##' + #DynamicTable + ''' , ''U'') IS NOT NULL ' +
' BEGIN DROP TABLE [##' + #DynamicTable + '] END'
EXEC sp_executesql #DynamicSQL
Certainly not the best solution, but this seems to work for me.
I would strongly suggest you have a read through http://www.sommarskog.se/arrays-in-sql-2005.html
Personally I like the approach of passing a comma delimited text list, then parsing it with text to table function and joining to it. The temp table approach can work if you create it first in the connection. But it feel a bit messier.
Result sets from dynamic SQL are returned to the client. I have done this quite a lot.
You're right about issues with sharing data through temp tables and variables and things like that between the SQL and the dynamic SQL it generates.
I think in trying to get your temp table working, you have probably got some things confused, because you can definitely get data from a SP which executes dynamic SQL:
USE SandBox
GO
CREATE PROCEDURE usp_DynTest(#table_type AS VARCHAR(255))
AS
BEGIN
DECLARE #sql AS VARCHAR(MAX) = 'SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''' + #table_type + ''''
EXEC (#sql)
END
GO
EXEC usp_DynTest 'BASE TABLE'
GO
EXEC usp_DynTest 'VIEW'
GO
DROP PROCEDURE usp_DynTest
GO
Also:
USE SandBox
GO
CREATE PROCEDURE usp_DynTest(#table_type AS VARCHAR(255))
AS
BEGIN
DECLARE #sql AS VARCHAR(MAX) = 'SELECT * INTO #temp FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''' + #table_type + '''; SELECT * FROM #temp;'
EXEC (#sql)
END
GO
EXEC usp_DynTest 'BASE TABLE'
GO
EXEC usp_DynTest 'VIEW'
GO
DROP PROCEDURE usp_DynTest
GO

SQL Server: is it possible to script table as UPDATE?

I need to export/script two tables to my local database to a remote anyway.
Anyway I cannot export them as INSERT INTO scripts because I cannot drop them in the remote database and populate them again (because of FK and integrity constraints). So, is it possibile to script tables as UPDATE statements for each row, instead of INSERT INTO? I'm using SQL Server 2008/2012
CREATE TABLE mytable(
ExtractTypeNum INTEGER NOT NULL --PRIMARY KEY
,FileOrderNum VARCHAR(11)
,PrevFileOrderNum VARCHAR(11)
,NextFileOrderNum VARCHAR(11)
,rownum1 INTEGER
,Statusflag1 VARCHAR(9)
);
INSERT INTO mytable(ExtractTypeNum,FileOrderNum,PrevFileOrderNum,NextFileOrderNum,rownum1,Statusflag1)
VALUES (1,'2016-09-191',NULL,'2016-09-192',1,'IsInitial');
INSERT INTO mytable(ExtractTypeNum,FileOrderNum,PrevFileOrderNum,NextFileOrderNum,rownum1,Statusflag1)
VALUES (2,'2016-09-192','2016-09-191','2016-09-201',2,NULL);
INSERT INTO mytable(ExtractTypeNum,FileOrderNum,PrevFileOrderNum,NextFileOrderNum,rownum1,Statusflag1)
VALUES (3,'2016-09-201','2016-09-192','2016-09-211',3,NULL);
select 'Update Table Xyz Set Abc='+Convert(varchar(25),rownum1)+' ' as X,*
from myTable
There is many ways to sync data between databases. As my experience, you can do by 2 main ways:
Using MERGE statement (it supports from mssql 2k8: https://msdn.microsoft.com/en-us/library/bb510625.aspx)
write dynamic query to generate data script for 2 target tables:
Select 'select * into #tmp from dbtarget.tbla where 1<0;' as data
Union
Select 'insert into #tmp values(' + convert(varchar, cola) + ', ' + convert(varchar, colb) + ', ' + convert(varchar, colc) + ');' as data from dbsource.tbla;
run the query above at database source to get output script data.
apply script data to target database.
using MERGE statement to merge data between #tmp table and target table.
Utilize Log Shipping feature to sync data between databases in the same structure and in one domain network.
https://msdn.microsoft.com/en-us/library/ms190640(v=sql.110).aspx
Many thanks to Alfaiz Ahmed this is my final working script:
select 'UPDATE ERGO.DBO.RESIDENZE SET CODISEDERESI='+CONVERT(varchar(50),CODISEDERESI)+
',DESCRIRESIDE='+isnull(CONVERT(varchar(100),''''+replace(DESCRIRESIDE,'''','''''')+''''),'''''')+
',INDIRIRESIDE='+isnull(CONVERT(varchar(100),''''+replace(INDIRIRESIDE,'''','''''')+''''),'''''')+
',NOMERESIDENZ='+isnull(CONVERT(varchar(50),''''+replace(NOMERESIDENZ,'''','''''')+''''),'''''')+
',VIARESIDENZA='+isnull(CONVERT(varchar(50),''''+replace(VIARESIDENZA,'''','''''')+''''),'''''')+
',CAPRESIDENZA='+isnull(CONVERT(varchar(50),''''+CAPRESIDENZA+''''),'''''')+
',CITTARESIDEN='+isnull(CONVERT(varchar(50),''''+replace(CITTARESIDEN,'''','''''')+''''),'''''')+
',EMAILRESIDEN='+isnull(CONVERT(varchar(100),''''+EMAILRESIDEN+''''),'''''')+
' WHERE CODICERESIDE='+CONVERT(varchar(50),CODICERESIDE)
from RESIDENZE
I had to use that replace() function because many Italian names have a single quote in their names so, for example, I wanted string D'AZEGLIO to become D''AZEGLIO in order to be correctly processed by SQL. Finally, before execute the query I press CTRL+SHIFT+F to save the output to a sql file as a generated script.

T-SQL: Creating a temp Table/ table Variable with Flexible structure

I am working on a reporting project based in SQL but I have restricted access to the DB; I can only make SELECT Queries and insert the data I retrieve into temp Tables/table variables. I cannot create/execute stored procedures or any sort of functions.
The query I am running is meant to pool together all Engineers and the different key skills that they have so that we can later on see what Skills each engineer has or which Engineers fall under a certain skill.
To this end, I am trying to create a table variable/temp table with a flexible structure, a structure based on previously obtained values in the same query.
For E.g.
1st Output:
Adam
Brad
Julio
Martinez
2nd Output (Skill separated by white space):
VOIP
TTS
DBA
Exchange
Server
Create temp table/table variable that uses 1st output as rows and 2nd output as columns or vice versa. I will then populate this new table according to different values on the main DB.
Please advise how this can be done, or provide any other solution to this problem.
Thank you
I believe you can.
First of all you need to create temp table with dynamic structure based on query. It can be done like this:
declare script template:
Set #ScriptTmpl = 'Alter table #tempTable Add [?] varchar(100);
build script that will insert columns you need based on query:
Select #TableScript = #TableScript + Replace(#ScriptTmpl, '?',
ColumnName) From ... Where ...
then execute script and then fill your new table with values from second query
UPD:
here is the full sample of temporary table dynamic creation. I used global temporary table in my sample:
declare #scriptTemplate nvarchar(MAX)
declare #script nvarchar(MAX)
declare #tableTemplate nvarchar(MAX)
SET #tableTemplate = 'create table ##tmptable (?)'
SET #scriptTemplate = '? nvarchar(500),'
SET #script = ''
Drop table ##tmptable
Select #script = #script + Replace(#scriptTemplate, '?', [Name])
From Account
Where name like 'ES_%'
SET #script = LEFT(#script, LEN(#script) - 1)
SET #script = Replace(#tableTemplate, '?', #script)
Select #script
exec(#script)
Select * from ##tmptable
Firstly, you may be able to achieve what you want through pivots, rather than temporary tables.
Secondly, if you really want to create a table with column name "Adam Brad", the solution is dynamic SQL, which you may not be able to do based on your permissions.

How do I insert the results from "EXEC()" in a temp table

I need som help with a problem, our company have a vendor that deliver a database to us. inside that database, the vendor has a table with alot of t sql scripts. What i want to do is the following, i want to make a select to find the script and then execut the script and store the result in a variable or temp tabel. I can not alter the script from the vedor, so I need the result into something i can manupilate. Another problem is that i dont know how many columns ther result will have. So it has to be flexible. Like one script have 5 columns and and the next script has 8 and so on.
exsample:
DECLARE #SQL nvarchar(MAX) = ( Select distinct script_details
from scripttable where .......)
This will give me the script I want to use, then I use
EXEC(#SQL)
to execute the script.
Then my problem is, the result from this I want into a variable or a table.
I have tryed to make a temp table like this:
create table #TmpTblSP (col1 varchar(MAX),col2 varchar(MAX),col3 varchar(MAX),col4 varchar(MAX),col5 varchar(MAX),col6 varchar(MAX),col7 varchar(MAX),col8 varchar(MAX),col9 varchar(MAX),col10 varchar(MAX),col11 varchar(MAX),col12 varchar(MAX))
then
insert into #TmpTblSP
EXEC(#SQL)
This gives me the following error:
Msg 213, Level 16, State 7, Line 1
Column name or number of supplied values does not match table definition.
But if i know how many columns there are and specify that into the insert it works.
insert into #TmpTblSP(Col1,Col2,Col3)
EXEC(#SQL)
But here you se my problem, I dont know how many columns there are in every script. I could make one script for every script the vendor has, but that will be alot, it's like 3000 scripts in that table and they change them often.
You could try something like:
DECLARE #SQL nvarchar(MAX) = (
Select distinct script_details
into #temptbl
from scripttable where .......
);
EXEC(#SQL);
If you don't know how many columns yous #sql gives then the only solution is use SELECT INTO. I use it in this way:
DECLARE #QRY nvarchar(MAX) = ( Select distinct script_details
from scripttable where .......)
SET #sql = 'SELECT * into ' + #temptablename + ' FROM (' + #qry + ') A '
It gives some flexibility
Remember that it is easy to check structure of the table created in this way in sys so you can build another #SQL from this info if needed.
I this as well recommended to split "SELECT INTO" to 2 parts
One is
SELECT INTO ......... WHERE 1=2
Second
INSERT INTO SELECT ......
Creation of table locks all DB. So it is good to create it as fast as possible and then insert into it.