how to get value from table, where table name is a value from another table and in which i have to concat a string
I tried the below methods
eg:
select * from concat('tab', 'Maintenance Details')
or
select * from (select concat('tab', 'Maintenance Details'));
In the above examples 'Maintenance Details' is changed based on its parent query.
what i want to perform is
select
(
select sum(md.fieldname) from md.tablename
)
from tabMaintenance md;
You need dynamic sql as exec sp_executesql #sql
Example:
declare #sql nvarhcar(3000)
declare #tableName nvarhcar(50) = select tableName from TableA
set #sql = 'select * from '+tableName + 'where conditionhere'
exec sp_executesql #sql
see more about sp_executesql here:
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-ver16
Related
I have a temp table with few table names as below:
Id TableName
-------------
1 TableA
2 TableB
3 TableC
These table names should be replaced in the query shown, and should get executed. I can achieve it with a while loop, but I don't want to use while. Is there any alternative concept?
I have the following SQL statement:
SELECT
TDU.ColHeader, TDU.ColValues
FROM
(SELECT
' + #ColumnsCasted + '
FROM
' + #TableName + ' ' +
#WhereCondition + ') TD
UNPIVOT
(ColValues FOR ColHeader IN (' + #ColumnsUnpivot + ')
) AS TDU;
The #TableName, #ColumnsCasted, #ColumnsUnpivot are based upon the table name which is stored in a temp table. I used while loop to iterate each table name and replace it here in the statement.
Can anyone suggest a method without using while loop?
You may try to generate and execute dynamic SQL. Next example is just for SELECT * FROM Table statement, you must change it for your query:
-- Create table
CREATE TABLE #TempTable (
Id int,
TableName nvarchar(50)
)
INSERT INTO #TempTable (Id, TableName)
VALUES
(1, 'TableA'),
(2, 'TableB'),
(3, 'TableC')
-- Dynamic SQL
DECLARE #stm nvarchar(max)
DECLARE #err int
SET #stm = N''
SELECT #stm =
#stm +
'SELECT * FROM ' +
QUOTENAME(TableName) +
'; '
FROM #TempTable
-- Statement execution
PRINT #stm
EXEC #err = sp_executesql #stm
IF #err <> 0 PRINT 'Error'
ELSE PRINT 'OK'
Generated statement:
SELECT * FROM [TableA]; SELECT * FROM [TableB]; SELECT * FROM [TableC];
There is non-documented function sp_MSforeachtable that executes query for each table in databse, maybe it can help you:
EXEC sp_MSforeachtable 'SELECT COUNT(*) FROM ?'
Hi below is a simple query to fetch value from local database and selects values from a DB2 linked server. I am unable to execute it. I am getting an error.
Incorrect syntax near 'AU000'.
If I run the query standalone like exec(#VAR) it works but Exec(#TSQL) doesn't. Please help. below is the query I am running.
DECLARE #TSQL varchar(8000) , #VAR char(200)
select #VAR = 'select top 1 ''AU000'' + CONVERT(VARCHAR(50),CPHN#) from upload.cancelledcontractheader'
SELECT #TSQL = '
SELECT * FROM OPENQUERY(
AS400TS_LNK,
''
select * from TWGTEST.AUPRDDBF.CONTACCT where ACTRNO ='''''+#VAR+'''''
''
)
'
EXEC (#TSQL)
Finally I want to achieve this
DECLARE #TSQL varchar(8000) , #VAR char(200)
Create table #siteId (id varchar(100))
DECLARE #SQL nvarchar(max) = N'insert into #siteId (id) select (''AU000'' + CONVERT(VARCHAR(50),CPHN#)) from upload.cancelledcontractheader'
exec (#SQL)
select #VAR = 'select ''AU000'' + CONVERT(VARCHAR(50),CPHN#) from upload.cancelledcontractheader'
SELECT #TSQL = '
SELECT * FROM OPENQUERY(
AS400TS_LNK,
''
insert into AUPRDDBF.CONTACCT (ACTRNO, ASEQN, ACTRAL, ASEQA, ATYPECOD, ASKU, AACDTID, AACCTVR, ACDTIDD, AACCTCD, ASTATUS, AAMOUNT, ACRTUSR, ACRTDTE, ACRTTIM, ACHGUSR, ACHGDTE,
ACHGTIM)
SELECT ACTRNO, ASEQN, ACTRAL, ASEQA, '9123', ASKU, AACDTID, AACCTVR, ACDTIDD, AACCTCD, 'C', AAMOUNT, ACRTUSR, ACRTDTE, ACRTTIM, 'SSCE2', ACHGDTE,
ACHGTIM
from AUPRDDBF.CONTACCT where ACTRNO in '''''+#siteId+'''''
''
)
'
EXEC (#TSQL)
drop table #siteId
I am querying a linked server:
DECLARE #result nvarchar(max);
SET #Sql = N'
SELECT *
FROM OPENQUERY(DATABASE_' + UPPER(#Environment) + ', ''
Complex Query against the linked server...
'');'
EXECUTE sp_executesql #sql, #result OUTPUT
Before inserting the results into the correct table I have to filter some rows of the results. I can't filter them in the original query because the results must be matched against values in the target table.
Something like:
INSERT INTO targetTable
SELECT * FROM #result AS r
WHERE r.Col1 NOT IN (SELECT Col1 FROM targetTable)
AND r.Col2 NOT IN (SELECT Col2 FROM targetTable)
I can't use the #results variable to query from because it's no table.
How can I do this?
Create a table variable or temporary table. Insert the records from your openquery. Here is an example with a table variable.
declare #tableVar as table (
field1 varchar(10)
, field2 int
etc
);
declare #sql as nvarchar(max);
set #sql = '
SELECT value1, value2, etc
FROM OPENQUERY(DATABASE_' + UPPER(#Environment) + ', ''
Complex Query against the linked server...
'');
insert into #tableVar
EXECUTE sp_executesql #sql
';
Solved my problem with a hint form here
Code:
DECLARE #linkedServer varchar(50) = 'linkedServerName';
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N'
INSERT INTO [DatabaseName].[Schema].[Table]
SELECT
t1.Column1
FROM OPENQUERY(' + #linkedServer + ',
''
complex query here
) AS t1
WHERE t1.Column1 NOT IN (SELECT Column1 FROM [DatabaseName].[Schema].[Table])
;
';
EXECUTE sp_executesql #sql;
Works like a charm.
Kind Regards
I want to achieve this -
SELECT * FROM A1234
I have the the ID 1234 saved in another table called Aliases which has two columns Alias,ID with one record like this.
Alias = TestTable, ID = 1234
So I am trying something like this
SELECT * FROM ('A'+ (SELECT ID FROM Aliases WHERE Alias = 'TestTable'))
Any help would be appreciated
You should use dynamic sql.
DECLARE #Q VARCHAR(MAX),#ID INT
SET #ID=(Select DISTINCT ID from Aliases where Alias = 'TestTable') -- CHECK TO RETURN JUST ON RESULT
SET #Q='SELECT * FROM A'+CAST(#ID AS VARCHAR(10))
EXEC(#Q)
You need dynamic SQL for this.
DECLARE #sql NVARCHAR(MAX);
SELECT TOP (1) #sql = N'SELECT * FROM A' + RTRIM(ID) + ';'
FROM dbo.Aliases WHERE Alias = 'TestTable';
EXEC sp_executesql #sql;
To build a set of statements that selects all of them, you can say:
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'';
SELECT #sql = #sql + N'
SELECT *, ''A' + RTRIM(ID) + ''' FROM A' + RTRIM(ID) + ';'
FROM dbo.Aliases;
PRINT #sql;
-- EXEC sp_executesql #sql;
sql 2005/ sql 2008
Declare #temp nvarchar(1000)
set #temp = 'ABC'
select col1,col2 from tableA
Along with select query, how to add a variable to the select query ?
expected output :-
select col1,col2,#temp as [col3] from tableA
Where #temp specifies the name of a column in tableA.
If you are trying to specify the column name dynamically, you could take a look at executing dynamic sql. However, you should make sure to read about the dangers of this approach first:
http://www.sommarskog.se/dynamic_sql.html
From that page, there is a sample that shows dynamically specifying the table name -- you could change it so it dynamically specifies the column name instead:
CREATE PROCEDURE general_select #tblname nvarchar(128),
#key varchar(10),
#debug bit = 0 AS
DECLARE #sql nvarchar(4000)
SET #sql = 'SELECT col1, col2, col3
FROM dbo.' + quotename(#tblname) + '
WHERE keycol = #key'
IF #debug = 1 PRINT #sql
EXEC sp_executesql #sql, N'#key varchar(10)', #key = #key
So for example if you had a table 'MyTable' with columns named 'x', 'y', and 'z', it might look like:
DECLARE #columnName nvarchar(128)
DECLARE #sql nvarchar(4000)
set #columnName = 'z'
SET #sql = 'SELECT x, y, ' + #columnName + ' from MyTable'
EXEC sp_executesql #sql, N'#columnName varchar(128)', #columnName = #columnName
Something like this:
select col1,col2 from tableA WHERE col1 = #temp
Or this:
select col1,col2,#temp as col3 from tableA WHERE col1 = #temp
Or this:
select col1,col2,#temp as col3 from tableA
Or if #temp is a column name, then maybe you're looking for a dynamic query?
SET #temp = 'select col1,col2, ' + #temp + ' as col3 from tableA'
EXEC sp_executesql #temp
...