Concatenate in SQL Server - sql

I have the following code in SQL
DECLARE c CURSOR FOR select MSISDN FROM
OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=' + #Path + ';HDR=YES', 'SELECT MSISDN FROM [sheet1$]')
i want to concatenate the path in the database , but the concatenation isn't working , any idea ?

You can't do string concatenation in OPENROWSET - the command expects string literals. I recently had a project at work converting some old SQL that used OPENROWSET and ran into that issue.
One way around this is by using OPENROWSET to dump the data into a table variable, and then declare your cursor from the table variable. Something like this (not tested):
DECLARE #data AS TABLE(MSISDN VARCHAR(255))
DECLARE #sql AS VARCHAR(4000)
SET #sql = 'SELECT MSISDN FROM '
SET #sql = #sql + ' OPENROWSET(''Microsoft.ACE.OLEDB.12.0'','
SET #sql = #sql + '''Excel 12.0;Database=' + #Path + ';HDR=YES'','
SET #sql = #sql + '''SELECT MSISDN FROM [sheet1$]'')'
INSERT INTO #data
EXECUTE sp_executesql #sql
DECLARE c CURSOR FOR SELECT MSISDN FROM #data

Related

Variable in SQL query syntax

I want to make a simple SQL query like:
SELECT * FROM table WHERE $variable_2 = $variable_1
instead of a default one:
SELECT * FROM table WHERE column_name = $variable_1
It seems like first example doesn't work at all. Is it even possible to modify SQL query syntax in such way?
as this reference answer for:
in link:
Use Variable as SQL column Name in query
answer1:
declare #ColumnName varchar(50)
declare #sql nvarchar(max)
set #ColumnName = 'SalesData_' + convert(varchar(2),datepart(dd,getdate()))
set #sql = 'select ' + #ColumnName + ' from SalesTable'
print #sql
EXEC sp_sqlexec #sql
answer 2:
declare #ColumnName varchar(50)
declare #sql nvarchar(max)
set #ColumnName = 'SalesData_' + convert(varchar(2),datepart(dd,getdate()))
set #sql = 'select ' + #ColumnName + ' from yourschema.SalesTable'
print #sql

OPENQUERY query stored in string fails with EXEC

I'm trying to pull back some data via a linked server that has 'Geography' fields present, consequntly I'm trying to use Open Query.
I'm also trying to pass in a variable...
Can anyone explain this:
This is my sql...
DECLARE #Sql VARCHAR(200)
DECLARE #tnum VARCHAR(20)= 'abc';
SET #Sql = 'SELECT * FROM NationalPolygon.dbo.Polygon WHERE TitleNumber = ''''' + #tnum + '''''';
SET #Sql = 'SELECT * FROM OPENQUERY(mylinkedserver01, ''' + REPLACE(#Sql, '?', '''') + ''')'
SELECT #Sql;
EXEC #Sql;
If I select #Sql and run it, it works.
If I run the #Sql via EXEC it fails with:
Database 'SELECT * FROM OPENQUERY(mylinkedserver01, 'SELECT * FROM NationalPolygon' does not exist. Make sure that the name is entered correctly.
Thanks
C
You need to surround #Sql with brackets
EXEC (#Sql);

T-SQL Setting a scalar variable with the value of another scalar variable

Im creating a stored procedure that retrieves data to fill a radar chart. It worked pretty well using static tables und rows like this:
(This is just a piece of the code)
SELECT
#aAvg = CAST(AVG(1. * foerderpy_1617) as DECIMAL(18,4)),
#aMin = CAST(MIN(1. * foerderpy_1617) as DECIMAL(18,4)),
#aMax = CAST(MAX(1. * foerderpy_1617) as DECIMAL(18,4))
FROM foerderpy a WHERE SUBSTRING(a.BSN,3,1) = 'g';
But now i want a dynamic sql. I want the stored procedure to always take the latest row of my table:
(These are just pieces of the code)
DECLARE #SQL AS NVARCHAR(MAX);
DECLARE #aAvg AS NVARCHAR(MAX);
DECLARE #aMin AS NVARCHAR(MAX);
DECLARE #aMax AS NVARCHAR(MAX);
DECLARE #tabname SYSNAME;
DECLARE #coluname SYSNAME;
DECLARE #counter INTEGER;
SET #tabname = 'foerderpy'
SET #counter = (
SELECT MAX(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #tabname
GROUP BY TABLE_NAME)
SET #coluname = (
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #tabname AND
ORDINAL_POSITION = #counter)
SET #aAvg = (SELECT CAST(AVG(1. * #coluname) as DECIMAL(18,4))FROM #tabname a WHERE SUBSTRING(a.BSN,3,1) = SUBSTRING(#restriction,3,1))
At the last line (the SET #aAvg), the stored procedure stops working and sql tells me "i have to declare #tabname", although i obv. declared it above. What is the problem im missing? Is it even possible to do what im trying?
The rest of the Code isn't causing any problems so i left it out. I need the #aAvg to calculate later in the procedure.
You need to run your last query using EXECUTE because EXECUTE:
Executes a command string or character string within a Transact-SQL batch
So you have to change the last line of your procedure in a way that the query is written in a string and called by execute.
DECLARE #sql VARCHAR(max) = 'SELECT CAST(AVG(1. * ' + #coluname + ') as DECIMAL(18,4))FROM '+ #tabname +' a WHERE SUBSTRING(a.BSN,3,1) = SUBSTRING('+#restriction+',3,1)';
EXECUTE(#sql);
If you would like to save the value in your variable #aAvg, you can use sp_executesql with an out parameter, this way:
DECLARE #sql VARCHAR(max) = 'SELECT CAST(AVG(1. * ' + #coluname + ') as DECIMAL(18,4))FROM '+ #tabname +' a WHERE SUBSTRING(a.BSN,3,1) = SUBSTRING('+#restriction+',3,1)';
exec sp_executesql #sql, N'#aAvg decimal(18,4) out', #aAvg out
select #aAvg

Get column value from string column name sql

Is this possible to get multiple columns value when we have column name as string
Like if i have a table Test and i have columns FirstName , LastName , Address .
Now what i want to get value of all three columns but i want to make this dynamic so that i just pass string column name i get values for that columns
Example
Select
(select column_name from metadata )
from source table
Pass the column names as parameters
DECLARE #COLS NVARCHAR(MAX)
DECLARE #TABLE NVARCHAR(MAX)
SET #COLS = 'COL1,COL2'
SET #TABLE = 'TABLENAME'
Now execute the query
DECLARE #QRY NVARCHAR(MAX)
SET #QRY = 'SELECT (SELECT '+#COLS+' FROM '+#TABLE+') FROM sourcetable'
EXEC SP_EXECUTESQL #QRY
You can build the query in code dynamically. However it needs to be robust so that it does not gets prone to SQL injection. Something like this:
string commandString = "select {0} from SomeTable";
SqlCommand command = new SqlCommand();
command.CommandText = string.Format(commandString, "selected column names");
command.EndExecuteReader();
In SQL:
declare #query nvarchar(500)
set #query = replace('select 0 from author','0','column names from some parameter')
execute sp_executesql #query
Update 2: Does this do what you need?
declare #query nvarchar(500)
DECLARE #columnNames varchar(1000)
set #columnNames = ''
SELECT #columnNames = #columnNames + column_name + ',' FROM metadata
set #query = replace('select 0 from source_table','0',SUBSTRING(#columnNames,0,LEN(#columnNames)-1))
execute sp_executesql #query

OpenRowset with dynamic sql variable insert query

I want to execute this query. Because only OPENROWSET don't work with variable :
EXEC
(
'
Insert into Table1
SELECT *
From OPENROWSET(MICROSOFT.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\Users\AA\Desktop\Table1.xlsx',
'SELECT *
FROM [Sheet1$] ) '
)
For insert in a table on SQL Server 2008 with a variable SQL. My objectif is to make the filepath dynamic like database='+#FilePath+'
Finally using this code in ado.Net in openFiledialog control
But it doesn't work I get a syntax error
I have solved but without insert query I think the same thing with insert always escape the quotes like that
EXEC
(
'SELECT *
From OPENROWSET(''MICROSOFT.ACE.OLEDB.12.0'',
''Excel 12.0;Database=C:\Users\AA\Desktop\Table1.xlsx'',
''SELECT *
FROM [Sheet1$]'') T
')
and with FilePath :
Declare
#FilePath nvarchar(50)
SET #FilePath='C:\Users\AA\Desktop\Table1.xlsx'
EXEC
(
'SELECT *
From OPENROWSET(''MICROSOFT.ACE.OLEDB.12.0'',
''Excel 12.0;Database='+#FilePath+''',
''SELECT *
FROM [Sheet1$]'') T
')
Your need to use dynamic sql for this And also it best to explicitly use Column Names in your INSERT INTO and SELECT statements. you can do something as follows.
DECLARE #SheetName NVARCHAR(MAX);
DECLARE #FilePath NVARCHAR(MAX);
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N' INSERT INTO Table1 ' +
N' SELECT * ' +
N' FROM OPENROWSET(''Microsoft.ACE.OLEDB.12.0'', ' +
N' ''Excel 8.0;Database='+ #FilePath + ';'' ,' +
N' ''SELECT* FROM ['+ #SheetName +']'')'
EXECUTE sp_executesql #Sql