OpenRowset with dynamic sql variable insert query - sql

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

Related

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);

Cannot execute open queries with parameter in linked server (DB2)

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

Must declare the scalar variable with Table-Valued Parameters and Stored Procedure

Could someone explain why the following gives me "Must declare the scalar variable #facilities." but works fine if I were to use VARCHAR instead of my created type? How can I fix this?
TIA
--CREATE TYPE integer_list AS TABLE (n int NOT NULL PRIMARY KEY)
--DROP PROCEDURE spTestTVP
CREATE PROCEDURE spTestTVP (
#facilities integer_list READONLY
--#facilities varchar(100)
)
AS
DECLARE #sql nvarchar(4000)
SET #sql = 'SELECT * FROM TestTable'
SET #sql = #sql + ' WHERE 1=1 '
IF #facilities IS NOT NULL
SET #sql = #sql + ' AND (FacilityNo IN (' + #facilities + ') OR FacilityNo IS NULL)'
EXEC sp_executesql #sql
DECLARE #items VARCHAR(MAX)
SELECT#items = COALESCE(#items+',' ,'') + n
FROM #facilities
DECLARE #sql nvarchar(4000)
SET #sql = 'SELECT * FROM TestTable'
SET #sql = #sql + ' WHERE 1=1 '
IF #facilities IS NOT NULL
SET #sql = #sql + ' AND (FacilityNo IN (' + #items + ') OR FacilityNo IS NULL)'
EXEC sp_executesql #sql
or not dynamic as follows:
SELECT t.* FROM TestTable as t
left outer join
#facilities as f
on
f.n = t.FacilityNo
where
t.FacilityNo is null
or
f.n is not null
When you are concatenating things in a dynamicSQl statment all pieces that build the statement must be either varchar or nvarchar. That is a limit of SQL.
On the other hand you don't need dynamic sql since you have created a table.
SELECT * FROM TestTable t
LEFT join #facilities f on f.n = t.facilityNO

Concatenate in SQL Server

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

confusion with quotes and double quotes in a query

i have a query that works beautifully:
CREATE Procedure BCP_Text_File
(
#table varchar(100),
#FileName varchar(100)
)
AS
If exists(Select * from information_Schema.tables where table_name=#table)
Begin
Declare #str varchar(1000)
set #str='Exec Master..xp_Cmdshell ''bcp "Select * from '+db_name()+'..'+#table+'" queryout "'+#FileName+'" -c'''
Exec(#str)
end
else
Select 'The table '+#table+' does not exist in the database'
but i need to add this in there:
select column_name
from information_schema.columns
where table_name = #table
order by ordinal_position
so far i have:
alter Procedure BCP_Text_File
(
#table varchar(100),
#FileName varchar(100)
)
AS
If exists(Select * from information_Schema.tables where table_name=#table)
Begin
Declare #str varchar(1000)
set #str='Exec Master..xp_Cmdshell ''bcp "
select column_name
from information_schema.columns
where table_name = '+db_name()+'..'+#table+'
order by ordinal_position
Select * from '+db_name()+'..'+#table+'" queryout "'+#FileName+'" -c'''
Exec(#str)
end
else
Select 'The table '+#table+' does not exist in the database'
but i think i am missplacing the single quotes and/or double quotes. i am adding this select statement so that my result has the field names as the first row.
thanks so much for any help or guidance.
Perhaps this is what you want? This assumes that (a) none of your column names have commas in them, and (b) the output of each column, when implicitly converted to a string, is okay.
ALTER PROCEDURE dbo.BCP_Text_File
#table NVARCHAR(255),
#filename VARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID(#table) IS NOT NULL
BEGIN
DECLARE
#sql NVARCHAR(MAX),
#cols NVARCHAR(MAX) = N'';
SELECT #cols += ',' + name
FROM sys.columns
WHERE [object_id] = OBJECT_ID(#table)
ORDER BY column_id;
SELECT #cols = STUFF(#cols, 1, 1, '');
SET #sql = N'EXEC master..xp_cmdshell ''bcp "SELECT '''''
+ REPLACE(#cols, ',', ''''',''''') + ''''' UNION ALL SELECT '
+ 'RTRIM(' + REPLACE(#cols, ',', '),RTRIM(') + ') FROM '
+ DB_NAME() + '..' + #table + '" queryout "' + #filename + '" -c''';
EXEC sp_executesql #sql;
END
ELSE
BEGIN
SELECT 'The table '+#table+' does not exist in the database';
END
END
GO
But I have to agree with the advice you've gotten from others on this and other questions - this approach is very brittle. You're trying to crack open a pistachio with a steamroller.
PS I removed references to INFORMATION_SCHEMA, because I think the catalog views are more reliable and more consistent.