How to select Columns using parameters in report builder - sql-server

In report builder can we select columns using parameters.
Example : select #field, column2, column3 from table_name
where #field is a parameter.
Also is there any way to do this:
select #field, column2, sum(column3) OVER (PARTITION BY #field) from table_name

This can only be done using dynamic sql:
CREATE PROCEDURE COLUMNRETURN
#ColumnName as nvarchar(100)
as
declare #sql as nvarchar(max)
set #sql = 'Select [' + #ColumnName + '] from [mytable]'
exec (#sql)
EXEC COLUMNRETURN 'mycolumn'

Related

Select same table name from all databases in SQL Server

I have this dynamic query, that is union from all my databases (that is start with "Db") the same table ("Tbl_SameTable").
DECLARE #tableName nvarchar(256) = 'Tbl_SameTable'
DECLARE #sql nvarchar(max) = ''
SELECT #sql = #sql + CASE WHEN #sql <> '' THEN 'UNION ALL ' ELSE '' END
+ 'SELECT * FROM [' + dbs.name + ']..[' + #tableName + '] '
FROM sys.sysdatabases dbs
WHERE left(dbs.name,2) = 'Db'
EXEC(#sql)
I want to add two things to this query:
Add a column of database name
Assign the query result to a "temp table" or "table variable"
I do not know if this is important but, the "Tbl_SameTable" is a 5 column table (int, nvarchar, int,nvarchar,nvarchar)
This is untested, however, you'll want something like this. As this is pseudo SQL, you'll need to replace {Columns} with the actual names (not *) for it to work. For the CREATE TABLE you'll need to define the data type of said columns too.
DECLARE #SchemaName sysname = N'dbo',
#TableName sysname = N'YourTable';
CREATE TABLE #Temp (DatabaseName sysname,
{Columns});
DECLARE #SQL nvarchar(MAX),
#CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SET #SQL = STUFF((SELECT #CRLF + N'UNION ALL' + #CRLF +
N'SELECT N' + QUOTENAME(d.[name],'''') + N' AS DatabaseName, {Columns}' + #CRLF +
N'FROM ' + QUOTENAME(d.[name]) + N'.' + QUOTENAME(#SchemaName) + N'.' + QUOTENAME(#TableName)
FROM sys.databases d
WHERE d.[name] LIKE 'Db%'
ORDER BY database_id
FOR XML PATH(N''),TYPE).value('(./text())[1]','nvarchar(MAX)'),1,13, N'') + N';'
--PRINT #SQL; --Your Best Friend
INSERT INTO #Temp(DatabaseName, {Columns})
EXEC sys.sp_executesql #SQL;
And, of course, if it doesn't work your best friend will be there to help you out.
How about using sp_MSforeachdb and adding the results to another table?
DROP TABLE IF EXISTS #tmp
CREATE TABLE #tmp (col1 INT, col2 INT,...)
DECLARE #command varchar(1000)
SELECT #command = 'IF ''?'' LIKE ''Db%'' BEGIN USE ?
EXEC(''INSERT INTO #tmp (col1, col2,...) SELECT col1, col2,... from Tbl_SameTable'') END'
EXEC sp_MSforeachdb #command
SELECT * FROM #tmp

SQL Server Table Parameter without defining fields [duplicate]

I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END

Run a query in every table that contains a specific column

I run this query to get all the tables that include a specific column name
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%myColumn%'
Then, for every single table, I want to run a query like this one:
SELECT * FROM table WHERE myColumn = xxx
Is there any way to do it automatically and run the second query to all the tables from the first query?
I have a fairly big database and I want to check if there is anywhere stored something about the specific Id on myColumn. And this column is used in about 200 tables.
I guess you need to use dynamic query for this. in this I saved the Schema result in a table variable and then loop through them to generate the required query. please try the below:
DECLARE #Template varchar(max)='SELECT * FROM [TABLE_NAME] WHERE [COLUMN_NAME] = ''xxx''';
DECLARE #CMD varchar(max);
DECLARE #id int=1, #TABLE_NAME varchar(255), #COLUMN_NAME varchar(255)
declare #Table table(id int identity(1,1), COLUMN_NAME varchar(255), TABLE_NAME varchar(255))
INSERT INTO #Table (TABLE_NAME, COLUMN_NAME)
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%Label%'
SELECT #id=ID, #TABLE_NAME = TABLE_NAME, #COLUMN_NAME = COLUMN_NAME FROM #Table WHERE ID = #id
While ##ROWCOUNT>0 BEGIN
SET #CMD = REPLACE(#Template, '[TABLE_NAME]', #TABLE_NAME)
SET #CMD = REPLACE(#CMD, '[COLUMN_NAME]', #COLUMN_NAME)
Print #cmd
EXEC (#CMD)
SELECT #id=ID, #TABLE_NAME = TABLE_NAME, #COLUMN_NAME = COLUMN_NAME FROM #Table WHERE ID = #id + 1
End
You could do this as follows. The script builds all the SELECT statements in a VARCHAR and then executes dynamically. Works when you for integers as well as varchars.
DECLARE #col_name SYSNAME='myColumn';
DECLARE #expected_value NVARCHAR(256)='xxx';
DECLARE #sel_stmts NVARCHAR(MAX) = (
SELECT
';SELECT '+
'* '+
'FROM '+
QUOTENAME(t.TABLE_SCHEMA)+'.'+QUOTENAME(t.TABLE_NAME) +
'WHERE '+
QUOTENAME(c.COLUMN_NAME)+'='''+REPLACE(#expected_value,'''','''''')+''''
FROM
INFORMATION_SCHEMA.TABLES AS t
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS c ON
c.TABLE_SCHEMA=t.TABLE_SCHEMA AND
c.TABLE_NAME=t.TABLE_NAME
WHERE
t.TABLE_TYPE='BASE TABLE' AND
c.COLUMN_NAME LIKE '%'+#col_name+'%'
FOR
XML PATH('')
)+';';
--SELECT #sel_stmts; -- review
EXEC sp_executesql #sel_stmts; -- execute it
I made a couple changes to Ahmed Saeed's answer that were helpful for me so posting them here
Adding the schema name for dbs with more than one schema
Adding extra [] around the schema/db names in case one of those names is also a keyword
Printing the tablename with the results
DECLARE #Template varchar(max)='SELECT ''[TABLE_NAME]'' as TableName, * FROM [[DBSCHEMA_NAME]].[[TABLE_NAME]] WHERE [COLUMN_NAME] = ''xxx''';
DECLARE #CMD varchar(max);
DECLARE #id int=1, #DBSCHEMA_NAME varchar(255), #TABLE_NAME varchar(255), #COLUMN_NAME varchar(255)
declare #Table table(id int identity(1,1), COLUMN_NAME varchar(255), TABLE_NAME varchar(255), DBSCHEMA_NAME varchar(255))
INSERT INTO #Table (TABLE_NAME, COLUMN_NAME, DBSCHEMA_NAME)
SELECT TABLE_NAME, COLUMN_NAME, TABLE_SCHEMA
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%colname%'
SELECT #id=ID, #DBSCHEMA_NAME = DBSCHEMA_NAME, #TABLE_NAME = TABLE_NAME, #COLUMN_NAME = COLUMN_NAME FROM #Table WHERE ID = #id
While ##ROWCOUNT>0 BEGIN
SET #CMD = REPLACE(#Template, '[TABLE_NAME]', #TABLE_NAME)
SET #CMD = REPLACE(#CMD, '[COLUMN_NAME]', #COLUMN_NAME)
SET #CMD = REPLACE(#CMD, '[DBSCHEMA_NAME]', #DBSCHEMA_NAME)
Print #cmd
EXEC (#CMD)
SELECT #id=ID, #DBSCHEMA_NAME = DBSCHEMA_NAME, #TABLE_NAME = TABLE_NAME, #COLUMN_NAME = COLUMN_NAME FROM #Table WHERE ID = #id + 1
End

How to SELECT * and get all field alphabetical ordered

This could be a strange question.
I have a table with 100+ columns. I would like to SELECT * all columns and get the resulting query with columns ordered alphabetically.
Is it possible in T-SQL?
Thanks
You could build a dynamic SQL statement using the information available in the system catalog view.
The sample code below shows how:
DECLARE #sql AS NVARCHAR(MAX)
DECLARE #cols AS NVARCHAR(MAX)
DECLARE #tbl NVARCHAR(MAX) = N'your_table' -- this is your source table
SELECT #cols= ISNULL(#cols + ',','') + QUOTENAME(c.name)
FROM sys.tables t
join sys.columns c ON c.object_id = t.object_id
WHERE t.name = #tbl
ORDER BY c.name
SET #sql = N'SELECT ' + #cols + ' FROM ' + #tbl
EXEC sp_executesql #sql
DynamicSQL (SQL Server) example:
declare #TABLE varchar(200) set #TABLE='persons'
declare #SQL nvarchar(max)
set #SQL='select '
select #SQL= #SQL + column_name + ','
from information_schema.columns where table_name=#TABLE order by column_name
select #SQL = left(#SQL,len(#SQL)-1) + ' from ' + #TABLE -- trims the trailing comma
--select #SQL -- If you want to see the query
exec sp_executesql #SQL
DECLARE #Table NVARCHAR(MAX)='T'--pass your table name
DECLARE #SQL NVARCHAR(MAX)='SELECT '
SELECT #SQL=#SQL+',' +NAME FROM
(
SELECT TOP 100 QUOTENAME(NAME) AS NAME
FROM sys.columns
WHERE object_id =
(
SELECT OBJECT_ID FROM sys.tables
WHERE NAME =#Table
)
ORDER BY NAME
) AS SS
SELECT #SQL=STUFF(#SQL,8,1,'')+' FROM '+#Table
EXEC sp_executesql #sql

Drop multiple tables with string

I have tables like lg-010-a..., lg-010-ac..., and so on, I have abc database,
I have a command window:
drop table from abc where Table_Name like 'lg-010-%'
Will this drop all the tables starting with lg-010-?
Try something like this:
declare #sql varchar(max)
declare #tablenames varchar(max)
select #tablenames = coalesce(#tablenames + ', ','') + Table_Name from INFORMATION_SCHEMA.TABLES
where Table_Name like ('lg-010-%')
set #sql = 'drop table ' + #tablenames
exec (#sql)
This queries the INFORMATION_SCHEMA.TABLES table to retrieve table names that match your criteria, then concatenates them together into a comma delimited string.
This string is than added to a 'Drop table ' statement and executed.
Drop table can take multiple comma delimited table names.
(I had originally had this query sys.tables but some research revealed that while they are currently equivalent, the Information_Schema method is quaranteed to work in future versions)
Unfortunately you can't do it like that. One way is:
SELECT 'DROP TABLE ' + name FROM sysobjects WHERE name LIKE '%lg-010-a%' AND [type] IN ('P')
This will just print out the DROP TABLE statement for each table - you can then copy and paste this output and run it. You can just put an EXECUTE in the loop instead of the PRINT, but I've done it this way so you can see what's going on/check the output first.
I had an issue where the accepted answer was not doing anything. I discovered that I had to add the prefix name of the database to the code to get it to work. If your tables are not dbo.tablename try this.
declare #sql varchar(max)
declare #tablenames varchar(max)
SELECT
#tablenames = COALESCE(#tablenames + ', ','') + 'YourDatabaseName.' + Table_Name
FROM
INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE 'AP2%'
AND (RIGHT(TABLE_NAME, 6) < 201708)
SET #sql = 'drop table ' + #tablenames
EXEC (#sql)
GO
Unfortunately you can't do it like that.
One way is:
DECLARE #TableName NVARCHAR(128)
SELECT TOP 1 #TableName = TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'lg-010-%'
ORDER BY TABLE_NAME ASC
WHILE (##ROWCOUNT > 0)
BEGIN
PRINT 'DROP TABLE [' + #TableName + ']'
SELECT TOP 1 #TableName = TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'lg-010-%'
AND TABLE_NAME > #TableName
ORDER BY TABLE_NAME ASC
END
This will just print out the DROP TABLE statement for each table - you can then copy and paste this output and run it. You can just put an EXECUTE in the loop instead of the PRINT, but I've done it this way so you can see what's going on/check the output first.
CREATE PROCEDURE dbo.drop_MsSqlTables1 #createDate smalldatetime
AS
declare #flag int =1
declare #tname varchar(50)
declare #sql varchar(max)
select row_number() over (order by name) as num, '[dbo].[' + name +']' as table_name into #temp from sys.tables where name like ('EmpInfo_%') and create_date<#createDate
declare #count int = (select count(*) from #temp)
select * from #temp
while #flag <= #count
begin
set #tname = (select table_name from #temp where num = #flag)
set #sql = 'drop table ' + #tname
exec (#sql)
set #flag = #flag+1
end

Resources