Showing posts with label statement. Show all posts
Showing posts with label statement. Show all posts

Friday, March 30, 2012

Passing parameter in LIKE statement with '%'

How do i handle this code:

CREATE PROCEDURE sp_Test

@.pchrTest1

AS

SELECT

fldTest1,

fldTest2

FROM

tblTest1

WHERE fldTest1 LIKE '%' + @.pchrTest1

This codes seems it does not work.

Thanks in advance

You can't use variable directly when executing SQL commands., instead will you need to construct a string representation of your command and execute it using the EXEC statement.
Your code above should work when done like this:



CREATE PROCEDURE sp_Test
@.pchrTest1
AS
EXEC('SELECT fldTest1, fldTest2 FROM tblTest1WHERE fldTest1 LIKE '''%' + @.pchrTest1)


Regards,
-chris|||You haven't specified a datatype for the parameter.
Try: @.pchrTest1 varchar(256)

It does work like this (without dynamic SQL).
|||

Just a warning...if any of this data is sensitive, this will open you up to "SQL injection" attacks:

http://www.nextgenss.com/papers/advanced_sql_injection.pdf

sql

Passing parameter in LIKE statement with '%'

How do i handle this code:

CREATE PROCEDURE sp_Test

@.pchrTest1

AS

SELECT

fldTest1,

fldTest2

FROM

tblTest1

WHERE fldTest1 LIKE '%' + @.pchrTest1

This codes seems it does not work.

Thanks in advance

You can't use variable directly when executing SQL commands., instead will you need to construct a string representation of your command and execute it using the EXEC statement.
Your code above should work when done like this:



CREATE PROCEDURE sp_Test
@.pchrTest1
AS
EXEC('SELECT fldTest1, fldTest2 FROM tblTest1WHERE fldTest1 LIKE '''%' + @.pchrTest1)


Regards,
-chris|||You haven't specified a datatype for the parameter.
Try: @.pchrTest1 varchar(256)

It does work like this (without dynamic SQL).|||

Just a warning...if any of this data is sensitive, this will open you up to "SQL injection" attacks:

http://www.nextgenss.com/papers/advanced_sql_injection.pdf

Passing parameter in LIKE statement with '%'

How do i handle this code:

CREATE PROCEDURE sp_Test

@.pchrTest1

AS

SELECT

fldTest1,

fldTest2

FROM

tblTest1

WHERE fldTest1 LIKE '%' + @.pchrTest1

This codes seems it does not work.

Thanks in advance

You can't use variable directly when executing SQL commands., instead will you need to construct a string representation of your command and execute it using the EXEC statement.
Your code above should work when done like this:



CREATE PROCEDURE sp_Test
@.pchrTest1
AS
EXEC('SELECT fldTest1, fldTest2 FROM tblTest1WHERE fldTest1 LIKE '''%' + @.pchrTest1)


Regards,
-chris|||You haven't specified a datatype for the parameter.
Try: @.pchrTest1 varchar(256)

It does work like this (without dynamic SQL).|||

Just a warning...if any of this data is sensitive, this will open you up to "SQL injection" attacks:

http://www.nextgenss.com/papers/advanced_sql_injection.pdf

Wednesday, March 28, 2012

Passing Multi Value Delimited string to a parameter

Hi Everyone,
I am using, or want to use a parameter as a filter in a sql statement, the
user will pick from a list that will then send a delimited list of numbers
e.g. "a1,a2,a3,a4" as the parameter that will be referenced in the sql
statement with a " field IN (@.parameter) " type thing.
Im sure this should work and its probably just the phrasing or something
that ive got wrong, can anyone help?
Steve DMulti-select parameters are a feature of RS 2005. This will not work in RS
2000. You can do dynamic sql to do this (note that you do open up to
injection attacks). Switch to generic query designer (to the right of the
...). Put in something like this.
="select somefield from sometable where anotherfield in (" &
Parameters.ParamName.Value & ")"
Note that RS will not detect your field list, so first have a regular query
to populate the field list.
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"Steve Dearman" <steve.dearman@.grant.co.uk> wrote in message
news:OFZt89YWGHA.1564@.TK2MSFTNGP03.phx.gbl...
> Hi Everyone,
> I am using, or want to use a parameter as a filter in a sql statement, the
> user will pick from a list that will then send a delimited list of numbers
> e.g. "a1,a2,a3,a4" as the parameter that will be referenced in the sql
> statement with a " field IN (@.parameter) " type thing.
> Im sure this should work and its probably just the phrasing or something
> that ive got wrong, can anyone help?
> Steve D
>

Friday, March 23, 2012

Passing DB Name/Owner Name in a prepareCall statement

When calling a stored procedure in sql server passing just the Stored
Procedure name, my stored procedure name works correctly. Below is
the String I use when performing Connection.prepareCall(String)
{CALL sp_name (?,?,?)}
However when I want to specify the db name and the user name (name of
the user who owns the sp), I get an error that the driver could not
find the stored procedure. Any clues as to how this could be fixed?
In other words, how can I set the default database name and owner name
to query against?
{CALL dbName.username.sp_name (?,?,?)}
Ryan wrote:

> When calling a stored procedure in sql server passing just the Stored
> Procedure name, my stored procedure name works correctly. Below is
> the String I use when performing Connection.prepareCall(String)
> {CALL sp_name (?,?,?)}
> However when I want to specify the db name and the user name (name of
> the user who owns the sp), I get an error that the driver could not
> find the stored procedure.
It's the DBMS, not the driver, that can or cannot find a stored procedure.
Your JDBC SQL seems fine. Show the actual exception you get. Maybe that will
help.
Any clues as to how this could be fixed?
> In other words, how can I set the default database name and owner name
> to query against?
> {CALL dbName.username.sp_name (?,?,?)}
|||Joe Weinstein <joeNOSPAM@.bea.com> wrote in message news:<412CF482.9070904@.bea.com>...[vbcol=seagreen]
> Ryan wrote:
>
> It's the DBMS, not the driver, that can or cannot find a stored procedure.
> Your JDBC SQL seems fine. Show the actual exception you get. Maybe that will
> help.
> Any clues as to how this could be fixed?
I get the following exception:
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for
JDBC][SQLServer]The procedure name
'dbName.username1.dbName.userName2.' contains more than the maximum
number of prefixes. The maximum is 3.
The call I pass to Connection.prepareCall is:
{CALL dbName.username2.sp_name (?,?,?)}
where dbname = the name of the database that I logged into. Username1
is the username that I logged in with. Username2 is the username of
the owner of the stored procedure and sp_name is the name of the
stored procedure.
|||Joe Weinstein <joeNOSPAM@.bea.com> wrote in message news:<412CF482.9070904@.bea.com>...[vbcol=seagreen]
> Ryan wrote:
>
> It's the DBMS, not the driver, that can or cannot find a stored procedure.
> Your JDBC SQL seems fine. Show the actual exception you get. Maybe that will
> help.
> Any clues as to how this could be fixed?
I get the following exception:
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for
JDBC][SQLServer]The procedure name
'dbName.username1.dbName.userName2.' contains more than the maximum
number of prefixes. The maximum is 3.
The call I pass to Connection.prepareCall is:
{CALL dbName.username2.sp_name (?,?,?)}
where dbname = the name of the database that I logged into. Username1
is the username that I logged in with. Username2 is the username of
the owner of the stored procedure and sp_name is the name of the
stored procedure.
|||Ryan wrote:

> Joe Weinstein <joeNOSPAM@.bea.com> wrote in message news:<412CF482.9070904@.bea.com>...
>
> I get the following exception:
> java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for
> JDBC][SQLServer]The procedure name
> 'dbName.username1.dbName.userName2.' contains more than the maximum
> number of prefixes. The maximum is 3.
> The call I pass to Connection.prepareCall is:
> {CALL dbName.username2.sp_name (?,?,?)}
> where dbname = the name of the database that I logged into. Username1
> is the username that I logged in with. Username2 is the username of
> the owner of the stored procedure and sp_name is the name of the
> stored procedure.
very odd. Does this code work for you?
It does for me... (logging in as a non-sa user...)
Statement s = c.createStatement();
s.execute("use tempdb");
s.execute("exec master.dbo.sp_who");
PreparedStatement p = c.prepareStatement("{ call master.dbo.sp_who() }");
p.execute();
CallableStatement cl = c.prepareCall("{ call master.dbo.sp_who() }");
cl.execute();
|||Thanks Joe,
I found the culprit in an extended class. It was prepending a default
databaseName.ownerName. causing this "weird" behavior. A wasted
thread,
{CALL dbname.ownername.sp_name (?,?,?)}
will work.
Joe Weinstein wrote:[vbcol=seagreen]
> Ryan wrote:
news:<412CF482.9070904@.bea.com>...[vbcol=seagreen]
Stored[vbcol=seagreen]
is[vbcol=seagreen]
of[vbcol=seagreen]
not[vbcol=seagreen]
procedure.[vbcol=seagreen]
that will[vbcol=seagreen]
name[vbcol=seagreen]
Username1[vbcol=seagreen]
of
> very odd. Does this code work for you?
> It does for me... (logging in as a non-sa user...)
> Statement s = c.createStatement();
> s.execute("use tempdb");
> s.execute("exec master.dbo.sp_who");
> PreparedStatement p = c.prepareStatement("{ call
master.dbo.sp_who() }");
> p.execute();
> CallableStatement cl = c.prepareCall("{ call master.dbo.sp_who()
}");
> cl.execute();

passing datetime variables into a bcp statement

Hi

I posted a question a while back about passing dates through a BCP SQL statement and received the answer that they should look as follows

declare @.sql as varchar(1000)

select @.sql = 'bcp "Exec CHC_Data_V2..TestSP ''05/01/07'', ''01/01/07''" queryout "c:\entitytext.txt" -SAJR\SQLEXPRESS -T -c -t'

exec master..xp_cmdshell @.sql

Now I need to do it differently and I have declared date variables and set the values and now i want to place the varaible names into the statement but i am receiving errors such as cannot convert character to datetime and once again i am looking for the correct way to type the bcp statement

I have the following example

Declare @.EndDate Datetime

Declare @.StartDate DateTime

Declare @.FilePath varchar (250)

Declare @.ServerName varchar (250)

Declare @.sql varchar(8000)

SET @.EndDate = '05/01/2007'

SET @.StartDate = '06/01/2007'

SET @.FilePath = 'C:\test.txt'

SET @.ServerName = 'SQLEXPRESSSERVERPATH'

select @.sql = 'bcp "Exec CHC_Data_V2..CHC_PRSACursor @.EndDate, @.StartDate " queryout "' + @.FilePath + '" -S' + @.ServerName + ' -T -c -t "|"'

exec master..xp_cmdshell @.sql

I have tried

select @.sql = 'bcp "Exec CHC_Data_V2..CHC_PRSACursor '' + @.EndDate+ '', '' + @.StartDate + ''" queryout "' + @.FilePath + '" -S' + @.ServerName + ' -T -c -t "|"'

And many many other variations but am mystified as to the correct format.

Can anyone help?

Syvers

Try:

select @.sql = 'bcp "Exec CHC_Data_V2..CHC_PRSACursor ' + @.EndDate + ', ' + @.StartDate + ' " queryout "' + @.FilePath + '" -S' + @.ServerName + ' -T -c -t "|"'

exec master..xp_cmdshell @.sql

|||

Code Snippet

select @.sql = 'bcp "Exec CHC_Data_V2..TestSP ''' + convert(varchar(10), @.EndDate, 101) + ''', '''+ convert(varchar(10), @.StartDate, 101) + '''" queryout "c:\entitytext.txt" -SAJR\SQLEXPRESS -T -c -t'

|||

Thanks Dale, my thinking was not on all cylinders this morning -had to rush out for a meeting.

|||

Team work!

|||Thank you for your help, works great now.

Tuesday, March 20, 2012

passing an array into a stored procedure

I am trying to pass a set of id values into a stored procedure.
Currently i am comma seperating these into a varchar to achieve this.
the statement is then executed as follows:
exec 'select * from table where ID in (' + @.VarCharParam + ') Order By
ID'
This dows work fine, but there must be a better way.
Any help would be appreciated
Regards
Grant Merwitz
Hi Grant
The approach you've taken certainly does have it's problems, not the least
of which is that it's subject to SQL injection if it's accessible outside
the DB. Do make sure you understand SQL injection as a minimum before
rolling code like that out.
However, TSQL doesn't have arrays. A common approach to this problem is to
pass in xml either in varchar or text variables which can be opened inside
the stored proc using the sp_xml_preparedocument system proc.
Otherwise, if you're confident you're not subject to injection & you know
you'll only pass in a short list of variables, the approach you've used does
have some merit in that it's light-weight & doesn't varry the overhead of a
few of it's alternatives.
HTH
Regards,
Greg Linwood
SQL Server MVP
"GrantMagic" <grant@.magicalia.com> wrote in message
news:%23PRCD1%23bEHA.3580@.TK2MSFTNGP11.phx.gbl...
> I am trying to pass a set of id values into a stored procedure.
> Currently i am comma seperating these into a varchar to achieve this.
> the statement is then executed as follows:
> exec 'select * from table where ID in (' + @.VarCharParam + ') Order By
> ID'
> This dows work fine, but there must be a better way.
> Any help would be appreciated
> Regards
> Grant Merwitz
>
|||> the statement is then executed as follows:
> exec 'select * from table where ID in (' + @.VarCharParam + ') Order By
> ID'
> This dows work fine, but there must be a better way.
SQL Server doesn't know what an array is. See http://www.aspfaq.com/2248
for an alternative approch, and the links therein for more information.
http://www.aspfaq.com/
(Reverse address to reply.)
|||SQL Server may not know what arrays are, but Erland Sommerskog does :-)
http://www.sommarskog.se/arrays-in-sql.html
It never hurts to set up a table of integers, with a clustered unique index.
One thing SQL Server DOES know how to do is iterate fast through
a set of rows.
You might want to consider the 'monster parameter list' approach.
It works if you can put a reasonable bound (under 1024) on the number
of array elements.
It causes you to generate a lot of repetitive SQL, but once the sproc's
query plan
has been generated, the resulting interpreted code is fast.
CREATE PROC DoThat
@.This varchar(99), @.That varchar(99)
,@.A00 INT=NULL, @.A01 INT=NULL, @.A02 INT=NULL, ...
,@.A10 INT=NULL, @.A11 INT=NULL, @.A12 INT=NULL, ...
...
AS
DECLARE @.A TABLE(val int)
INSERT @.A SELECT *
FROM ( SELECT @.A00 val
UNION ALL SELECT @.A01
UNION ALL SELECT @.A02
...
) X
WHERE val IS NOT NULL
... go wild
If you can't use a default marker like NULL, you need a slightly different
approach:
CREATE PROC DoThat
@.This varchar(99), @.That varchar(99), @.ArgCount INT
,@.A00 INT=NULL, @.A01 INT=NULL, @.A02 INT=NULL, ...
,@.A10 INT=NULL, @.A11 INT=NULL, @.A12 INT=NULL, ...
...
AS
DECLARE @.A TABLE(val int)
INSERT @.A SELECT val
FROM ( SELECT @.A00 val, 00 AS seq
UNION ALL SELECT @.A01, 01
UNION ALL SELECT @.A02, 02
...
) X
WHERE seq < @.ArgCount
"Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:u5XVhD$bEHA.2972@.TK2MSFTNGP12.phx.gbl...[vbcol=seagreen]
By
> SQL Server doesn't know what an array is. See http://www.aspfaq.com/2248
> for an alternative approch, and the links therein for more information.
> --
> http://www.aspfaq.com/
> (Reverse address to reply.)
>

passing an array into a stored procedure

I am trying to pass a set of id values into a stored procedure.
Currently i am comma seperating these into a varchar to achieve this.
the statement is then executed as follows:
exec 'select * from table where ID in (' + @.VarCharParam + ') Order By
ID'
This dows work fine, but there must be a better way.
Any help would be appreciated
Regards
Grant MerwitzHi Grant
The approach you've taken certainly does have it's problems, not the least
of which is that it's subject to SQL injection if it's accessible outside
the DB. Do make sure you understand SQL injection as a minimum before
rolling code like that out.
However, TSQL doesn't have arrays. A common approach to this problem is to
pass in xml either in varchar or text variables which can be opened inside
the stored proc using the sp_xml_preparedocument system proc.
Otherwise, if you're confident you're not subject to injection & you know
you'll only pass in a short list of variables, the approach you've used does
have some merit in that it's light-weight & doesn't varry the overhead of a
few of it's alternatives.
HTH
Regards,
Greg Linwood
SQL Server MVP
"GrantMagic" <grant@.magicalia.com> wrote in message
news:%23PRCD1%23bEHA.3580@.TK2MSFTNGP11.phx.gbl...
> I am trying to pass a set of id values into a stored procedure.
> Currently i am comma seperating these into a varchar to achieve this.
> the statement is then executed as follows:
> exec 'select * from table where ID in (' + @.VarCharParam + ') Order By
> ID'
> This dows work fine, but there must be a better way.
> Any help would be appreciated
> Regards
> Grant Merwitz
>|||> the statement is then executed as follows:
> exec 'select * from table where ID in (' + @.VarCharParam + ') Order By
> ID'
> This dows work fine, but there must be a better way.
SQL Server doesn't know what an array is. See http://www.aspfaq.com/2248
for an alternative approch, and the links therein for more information.
--
http://www.aspfaq.com/
(Reverse address to reply.)|||SQL Server may not know what arrays are, but Erland Sommerskog does :-)
http://www.sommarskog.se/arrays-in-sql.html
It never hurts to set up a table of integers, with a clustered unique index.
One thing SQL Server DOES know how to do is iterate fast through
a set of rows.
You might want to consider the 'monster parameter list' approach.
It works if you can put a reasonable bound (under 1024) on the number
of array elements.
It causes you to generate a lot of repetitive SQL, but once the sproc's
query plan
has been generated, the resulting interpreted code is fast.
CREATE PROC DoThat
@.This varchar(99), @.That varchar(99)
,@.A00 INT=NULL, @.A01 INT=NULL, @.A02 INT=NULL, ...
,@.A10 INT=NULL, @.A11 INT=NULL, @.A12 INT=NULL, ...
...
AS
DECLARE @.A TABLE(val int)
INSERT @.A SELECT *
FROM ( SELECT @.A00 val
UNION ALL SELECT @.A01
UNION ALL SELECT @.A02
...
) X
WHERE val IS NOT NULL
... go wild
If you can't use a default marker like NULL, you need a slightly different
approach:
CREATE PROC DoThat
@.This varchar(99), @.That varchar(99), @.ArgCount INT
,@.A00 INT=NULL, @.A01 INT=NULL, @.A02 INT=NULL, ...
,@.A10 INT=NULL, @.A11 INT=NULL, @.A12 INT=NULL, ...
...
AS
DECLARE @.A TABLE(val int)
INSERT @.A SELECT val
FROM ( SELECT @.A00 val, 00 AS seq
UNION ALL SELECT @.A01, 01
UNION ALL SELECT @.A02, 02
...
) X
WHERE seq < @.ArgCount
"Aaron [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:u5XVhD$bEHA.2972@.TK2MSFTNGP12.phx.gbl...
> > the statement is then executed as follows:
> > exec 'select * from table where ID in (' + @.VarCharParam + ') Order
By
> > ID'
> >
> > This dows work fine, but there must be a better way.
> SQL Server doesn't know what an array is. See http://www.aspfaq.com/2248
> for an alternative approch, and the links therein for more information.
> --
> http://www.aspfaq.com/
> (Reverse address to reply.)
>

Passing a variable to the from statement

Hi,

I have the following sql that I execute against a flat file. The flat file has a fixed length header and trailer but variable length data section. I execute this sql to get the header and trailer details the data section is put through a process in integration services:

SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

,substring(bulkcolumn,charindex('ICMST',bulkcolumn)+6,4)--<RecordCount, varchar(6),>

,getdate()

FROM OPENROWSET(BULK N'c:\filename.txt',single_clob) as doc

My problem is that I want to be able to pass a variable to the filename, but cannot find a way to do it. It doesn't seem to like a normal stored procedure parameter passed to it, i.e BULK N'@.param1',single_clob, i get

'Cannot bulk load. The file "@.param" does not exist.'

The reason for me getting the header details like this is that integration services doesn't seem to fit well when we have a combination of variable and fixed length records.

Any other suggestions as to how I could solve this would be greatly appreciated.

Paul

dynamic sql would be a TSQL solution, though I would imagine SSIS has a "file emulator task" as well...

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = 'SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

,substring(bulkcolumn,charindex('ICMST',bulkcolumn)+6,4)--<RecordCount, varchar(6),>

,getdate()

FROM OPENROWSET(BULK N' + ''' + @.File + ''' + ',single_clob) as doc'

exec sp_executesql @.SQL

|||

I couldn't get this to work. It still doesn't recognise the @.file parameter passed in to the select

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = '

declare @.file nvarchar(500)

set @.file = ''c:\interface files\CostCentreImportFile.txt''

select @.file

SELECT

*

FROM OPENROWSET(BULK N'+''' + @.file + ''' + ',single_clob) as doc'

exec sp_executesql @.SQL

It returns....

Msg 4860, Level 16, State 1, Line 5

Cannot bulk load. The file " + @.file + " does not exist.

Even if I were to get that sorted I fear I'd still have a problem as it doesn't seem to recognise the 'bulkcolumn' keyword

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = '

declare @.file nvarchar(500)

set @.file = ''c:\interface files\CostCentreImportFile.txt''

SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

FROM OPENROWSET(BULK N''c:\interface files\CostCentreImportFile.txt'',single_clob) as doc'

--

exec sp_executesql @.SQL

Msg 207, Level 16, State 1, Line 5

Invalid column name 'bulkcolumn'.

The File data source in SSIS, I felt, wasn't adequate as I have two fixed length headers(different format), a variable length data section and then a fixed length trailer. I'd have to define four different file formats and ignore the other record formats on processing. Although I'm slowly talking myself into that approach

|||

THIS WORKS...

DECLARE

@.SQL NVARCHAR(500),

@.file nvarchar(500)

SET @.file = 'c:\interface files\CostCentreImportFile.txt'

SET @.SQL = 'SELECT * FROM OPENROWSET(BULK N''' + @.file + ''',single_clob) AS doc'

PRINT @.SQL

EXEC sp_executesql @.SQL

|||

Paul,

Did this work for you? If not please provide more info or mark answer.

thanks,

derek

|||

Apologies for the delay, I must admit I don't monitor my older posts.

Yes, thank you very much, that works.

|||

This not working for me.

I need something like this select but I would like to get content of this select into variable.

Could someone help me?

Code Snippet

SELECT @.strXML = x

FROM OPENROWSET(BULK @.filename, SINGLE_CLOB) AS result(x)

|||Hello Culprit, the problem with your statement is that it sends a variable (@.filename) as a parameter to the OPENROWSET function. This is not possible, because OPENROWSET does not allow its parameters to be variables (only literals).

My suggestion to you is that you create another variable, let's say [@.sql varchar(255)]. This variable will store the text of the whole OPENROWSET statement. Having this variable all you have to do is execute the newly created statement. Here's the code:

DECLARE @.sql varchar(255)
SELECT @.sql = 'OPENROWSET(BULK ' + @.filename + ', SINGLE_CLOB)'

SELECT @.strXML = x
FROM EXEC(@.sql) AS result(x)

I hope this helps. Let me know how it goes. Ciao.

Passing a variable to the from statement

Hi,

I have the following sql that I execute against a flat file. The flat file has a fixed length header and trailer but variable length data section. I execute this sql to get the header and trailer details the data section is put through a process in integration services:

SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

,substring(bulkcolumn,charindex('ICMST',bulkcolumn)+6,4)--<RecordCount, varchar(6),>

,getdate()

FROM OPENROWSET(BULK N'c:\filename.txt',single_clob) as doc

My problem is that I want to be able to pass a variable to the filename, but cannot find a way to do it. It doesn't seem to like a normal stored procedure parameter passed to it, i.e BULK N'@.param1',single_clob, i get

'Cannot bulk load. The file "@.param" does not exist.'

The reason for me getting the header details like this is that integration services doesn't seem to fit well when we have a combination of variable and fixed length records.

Any other suggestions as to how I could solve this would be greatly appreciated.

Paul

dynamic sql would be a TSQL solution, though I would imagine SSIS has a "file emulator task" as well...

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = 'SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

,substring(bulkcolumn,charindex('ICMST',bulkcolumn)+6,4)--<RecordCount, varchar(6),>

,getdate()

FROM OPENROWSET(BULK N' + ''' + @.File + ''' + ',single_clob) as doc'

exec sp_executesql @.SQL

|||

I couldn't get this to work. It still doesn't recognise the @.file parameter passed in to the select

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = '

declare @.file nvarchar(500)

set @.file = ''c:\interface files\CostCentreImportFile.txt''

select @.file

SELECT

*

FROM OPENROWSET(BULK N'+''' + @.file + ''' + ',single_clob) as doc'

exec sp_executesql @.SQL

It returns....

Msg 4860, Level 16, State 1, Line 5

Cannot bulk load. The file " + @.file + " does not exist.

Even if I were to get that sorted I fear I'd still have a problem as it doesn't seem to recognise the 'bulkcolumn' keyword

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = '

declare @.file nvarchar(500)

set @.file = ''c:\interface files\CostCentreImportFile.txt''

SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

FROM OPENROWSET(BULK N''c:\interface files\CostCentreImportFile.txt'',single_clob) as doc'

--

exec sp_executesql @.SQL

Msg 207, Level 16, State 1, Line 5

Invalid column name 'bulkcolumn'.

The File data source in SSIS, I felt, wasn't adequate as I have two fixed length headers(different format), a variable length data section and then a fixed length trailer. I'd have to define four different file formats and ignore the other record formats on processing. Although I'm slowly talking myself into that approach

|||

THIS WORKS...

DECLARE

@.SQL NVARCHAR(500),

@.file nvarchar(500)

SET @.file = 'c:\interface files\CostCentreImportFile.txt'

SET @.SQL = 'SELECT * FROM OPENROWSET(BULK N''' + @.file + ''',single_clob) AS doc'

PRINT @.SQL

EXEC sp_executesql @.SQL

|||

Paul,

Did this work for you? If not please provide more info or mark answer.

thanks,

derek

|||

Apologies for the delay, I must admit I don't monitor my older posts.

Yes, thank you very much, that works.

|||

This not working for me.

I need something like this select but I would like to get content of this select into variable.

Could someone help me?

Code Snippet

SELECT @.strXML = x

FROM OPENROWSET(BULK @.filename, SINGLE_CLOB) AS result(x)

|||Hello Culprit, the problem with your statement is that it sends a variable (@.filename) as a parameter to the OPENROWSET function. This is not possible, because OPENROWSET does not allow its parameters to be variables (only literals).

My suggestion to you is that you create another variable, let's say [@.sql varchar(255)]. This variable will store the text of the whole OPENROWSET statement. Having this variable all you have to do is execute the newly created statement. Here's the code:

DECLARE @.sql varchar(255)
SELECT @.sql = 'OPENROWSET(BULK ' + @.filename + ', SINGLE_CLOB)'

SELECT @.strXML = x
FROM EXEC(@.sql) AS result(x)

I hope this helps. Let me know how it goes. Ciao.

Passing a variable to the from statement

Hi,

I have the following sql that I execute against a flat file. The flat file has a fixed length header and trailer but variable length data section. I execute this sql to get the header and trailer details the data section is put through a process in integration services:

SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

,substring(bulkcolumn,charindex('ICMST',bulkcolumn)+6,4)--<RecordCount, varchar(6),>

,getdate()

FROM OPENROWSET(BULK N'c:\filename.txt',single_clob) as doc

My problem is that I want to be able to pass a variable to the filename, but cannot find a way to do it. It doesn't seem to like a normal stored procedure parameter passed to it, i.e BULK N'@.param1',single_clob, i get

'Cannot bulk load. The file "@.param" does not exist.'

The reason for me getting the header details like this is that integration services doesn't seem to fit well when we have a combination of variable and fixed length records.

Any other suggestions as to how I could solve this would be greatly appreciated.

Paul

dynamic sql would be a TSQL solution, though I would imagine SSIS has a "file emulator task" as well...

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = 'SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

,substring(bulkcolumn,charindex('ICMST',bulkcolumn)+6,4)--<RecordCount, varchar(6),>

,getdate()

FROM OPENROWSET(BULK N' + ''' + @.File + ''' + ',single_clob) as doc'

exec sp_executesql @.SQL

|||

I couldn't get this to work. It still doesn't recognise the @.file parameter passed in to the select

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = '

declare @.file nvarchar(500)

set @.file = ''c:\interface files\CostCentreImportFile.txt''

select @.file

SELECT

*

FROM OPENROWSET(BULK N'+''' + @.file + ''' + ',single_clob) as doc'

exec sp_executesql @.SQL

It returns....

Msg 4860, Level 16, State 1, Line 5

Cannot bulk load. The file " + @.file + " does not exist.

Even if I were to get that sorted I fear I'd still have a problem as it doesn't seem to recognise the 'bulkcolumn' keyword

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = '

declare @.file nvarchar(500)

set @.file = ''c:\interface files\CostCentreImportFile.txt''

SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

FROM OPENROWSET(BULK N''c:\interface files\CostCentreImportFile.txt'',single_clob) as doc'

--

exec sp_executesql @.SQL

Msg 207, Level 16, State 1, Line 5

Invalid column name 'bulkcolumn'.

The File data source in SSIS, I felt, wasn't adequate as I have two fixed length headers(different format), a variable length data section and then a fixed length trailer. I'd have to define four different file formats and ignore the other record formats on processing. Although I'm slowly talking myself into that approach

|||

THIS WORKS...

DECLARE

@.SQL NVARCHAR(500),

@.file nvarchar(500)

SET @.file = 'c:\interface files\CostCentreImportFile.txt'

SET @.SQL = 'SELECT * FROM OPENROWSET(BULK N''' + @.file + ''',single_clob) AS doc'

PRINT @.SQL

EXEC sp_executesql @.SQL

|||

Paul,

Did this work for you? If not please provide more info or mark answer.

thanks,

derek

|||

Apologies for the delay, I must admit I don't monitor my older posts.

Yes, thank you very much, that works.

|||

This not working for me.

I need something like this select but I would like to get content of this select into variable.

Could someone help me?

Code Snippet

SELECT @.strXML = x

FROM OPENROWSET(BULK @.filename, SINGLE_CLOB) AS result(x)

|||Hello Culprit, the problem with your statement is that it sends a variable (@.filename) as a parameter to the OPENROWSET function. This is not possible, because OPENROWSET does not allow its parameters to be variables (only literals).

My suggestion to you is that you create another variable, let's say [@.sql varchar(255)]. This variable will store the text of the whole OPENROWSET statement. Having this variable all you have to do is execute the newly created statement. Here's the code:

DECLARE @.sql varchar(255)
SELECT @.sql = 'OPENROWSET(BULK ' + @.filename + ', SINGLE_CLOB)'

SELECT @.strXML = x
FROM EXEC(@.sql) AS result(x)

I hope this helps. Let me know how it goes. Ciao.

Passing a variable to the from statement

Hi,

I have the following sql that I execute against a flat file. The flat file has a fixed length header and trailer but variable length data section. I execute this sql to get the header and trailer details the data section is put through a process in integration services:

SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

,substring(bulkcolumn,charindex('ICMST',bulkcolumn)+6,4)--<RecordCount, varchar(6),>

,getdate()

FROM OPENROWSET(BULK N'c:\filename.txt',single_clob) as doc

My problem is that I want to be able to pass a variable to the filename, but cannot find a way to do it. It doesn't seem to like a normal stored procedure parameter passed to it, i.e BULK N'@.param1',single_clob, i get

'Cannot bulk load. The file "@.param" does not exist.'

The reason for me getting the header details like this is that integration services doesn't seem to fit well when we have a combination of variable and fixed length records.

Any other suggestions as to how I could solve this would be greatly appreciated.

Paul

dynamic sql would be a TSQL solution, though I would imagine SSIS has a "file emulator task" as well...

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = 'SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

,substring(bulkcolumn,charindex('ICMST',bulkcolumn)+6,4)--<RecordCount, varchar(6),>

,getdate()

FROM OPENROWSET(BULK N' + ''' + @.File + ''' + ',single_clob) as doc'

exec sp_executesql @.SQL

|||

I couldn't get this to work. It still doesn't recognise the @.file parameter passed in to the select

DECLARE @.SQL NVARCHAR(500)

SET @.SQL ='

declare @.file nvarchar(500)

set @.file = ''c:\interface files\CostCentreImportFile.txt''

select @.file

SELECT

*

FROM OPENROWSET(BULK N'+''' + @.file + '''+',single_clob) as doc'

execsp_executesql @.SQL

It returns....

Msg 4860, Level 16, State 1, Line 5

Cannot bulk load. The file " + @.file + " does not exist.

Even if I were to get that sorted I fear I'd still have a problem as it doesn't seem to recognise the 'bulkcolumn' keyword

DECLARE @.SQL NVARCHAR(500)

SET @.SQL ='

declare @.file nvarchar(500)

set @.file = ''c:\interface files\CostCentreImportFile.txt''

SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

FROM OPENROWSET(BULK N''c:\interface files\CostCentreImportFile.txt'',single_clob) as doc'

--

execsp_executesql @.SQL

Msg 207, Level 16, State 1, Line 5

Invalid column name 'bulkcolumn'.

The File data source in SSIS, I felt, wasn't adequate as I have two fixed length headers(different format), a variable length data section and then a fixed length trailer. I'd have to define four different file formats and ignore the other record formats on processing. Although I'm slowly talking myself into that approach

|||

THIS WORKS...

DECLARE

@.SQL NVARCHAR(500),

@.file nvarchar(500)

SET @.file ='c:\interface files\CostCentreImportFile.txt'

SET @.SQL ='SELECT * FROM OPENROWSET(BULK N'''+ @.file +''',single_clob) AS doc'

PRINT @.SQL

EXECsp_executesql @.SQL

|||

Paul,

Did this work for you? If not please provide more info or mark answer.

thanks,

derek

|||

Apologies for the delay, I must admit I don't monitor my older posts.

Yes, thank you very much, that works.

|||

This not working for me.

I need something like this select but I would like to get content of this select into variable.

Could someone help me?

Code Snippet

SELECT @.strXML = x

FROMOPENROWSET(BULK@.filename,SINGLE_CLOB)AS result(x)

|||Hello Culprit, the problem with your statement is that it sends a variable (@.filename) as a parameter to the OPENROWSET function. This is not possible, because OPENROWSET does not allow its parameters to be variables (only literals).

My suggestion to you is that you create another variable, let's say [@.sql varchar(255)]. This variable will store the text of the whole OPENROWSET statement. Having this variable all you have to do is execute the newly created statement. Here's the code:

DECLARE @.sql varchar(255)
SELECT @.sql ='OPENROWSET(BULK ' +@.filename +', SINGLE_CLOB)'

SELECT @.strXML= x
FROM EXEC(@.sql) AS result(x)

I hope this helps. Let me know how it goes. Ciao.

Passing a variable to the from statement

Hi,

I have the following sql that I execute against a flat file. The flat file has a fixed length header and trailer but variable length data section. I execute this sql to get the header and trailer details the data section is put through a process in integration services:

SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

,substring(bulkcolumn,charindex('ICMST',bulkcolumn)+6,4)--<RecordCount, varchar(6),>

,getdate()

FROM OPENROWSET(BULK N'c:\filename.txt',single_clob) as doc

My problem is that I want to be able to pass a variable to the filename, but cannot find a way to do it. It doesn't seem to like a normal stored procedure parameter passed to it, i.e BULK N'@.param1',single_clob, i get

'Cannot bulk load. The file "@.param" does not exist.'

The reason for me getting the header details like this is that integration services doesn't seem to fit well when we have a combination of variable and fixed length records.

Any other suggestions as to how I could solve this would be greatly appreciated.

Paul

dynamic sql would be a TSQL solution, though I would imagine SSIS has a "file emulator task" as well...

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = 'SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

,substring(bulkcolumn,charindex('ICMST',bulkcolumn)+6,4)--<RecordCount, varchar(6),>

,getdate()

FROM OPENROWSET(BULK N' + ''' + @.File + ''' + ',single_clob) as doc'

exec sp_executesql @.SQL

|||

I couldn't get this to work. It still doesn't recognise the @.file parameter passed in to the select

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = '

declare @.file nvarchar(500)

set @.file = ''c:\interface files\CostCentreImportFile.txt''

select @.file

SELECT

*

FROM OPENROWSET(BULK N'+''' + @.file + ''' + ',single_clob) as doc'

exec sp_executesql @.SQL

It returns....

Msg 4860, Level 16, State 1, Line 5

Cannot bulk load. The file " + @.file + " does not exist.

Even if I were to get that sorted I fear I'd still have a problem as it doesn't seem to recognise the 'bulkcolumn' keyword

DECLARE @.SQL NVARCHAR(500)

SET @.SQL = '

declare @.file nvarchar(500)

set @.file = ''c:\interface files\CostCentreImportFile.txt''

SELECT

substring(bulkcolumn,1,5)--<HeaderIdentifier, char(5),>

,substring(bulkcolumn,6,10)--<SenderIdentifier, char(10),>

,substring(bulkcolumn,16,10)--<RecipientIdentifier, char(10),>

,substring(bulkcolumn,26,30)--<FileType, char(30),>

,substring(bulkcolumn,56,8)--<CreationDate, char(8),>

,substring(bulkcolumn,64,6)--<CreationTime, char(6),>

,substring(bulkcolumn,70,8) as SeqNo--<SequenceNumber, int,>

,substring(bulkcolumn,82,1)--<FeedType, char(1),>

FROM OPENROWSET(BULK N''c:\interface files\CostCentreImportFile.txt'',single_clob) as doc'

--

exec sp_executesql @.SQL

Msg 207, Level 16, State 1, Line 5

Invalid column name 'bulkcolumn'.

The File data source in SSIS, I felt, wasn't adequate as I have two fixed length headers(different format), a variable length data section and then a fixed length trailer. I'd have to define four different file formats and ignore the other record formats on processing. Although I'm slowly talking myself into that approach

|||

THIS WORKS...

DECLARE

@.SQL NVARCHAR(500),

@.file nvarchar(500)

SET @.file = 'c:\interface files\CostCentreImportFile.txt'

SET @.SQL = 'SELECT * FROM OPENROWSET(BULK N''' + @.file + ''',single_clob) AS doc'

PRINT @.SQL

EXEC sp_executesql @.SQL

|||

Paul,

Did this work for you? If not please provide more info or mark answer.

thanks,

derek

|||

Apologies for the delay, I must admit I don't monitor my older posts.

Yes, thank you very much, that works.

|||

This not working for me.

I need something like this select but I would like to get content of this select into variable.

Could someone help me?

Code Snippet

SELECT @.strXML = x

FROM OPENROWSET(BULK @.filename, SINGLE_CLOB) AS result(x)

|||Hello Culprit, the problem with your statement is that it sends a variable (@.filename) as a parameter to the OPENROWSET function. This is not possible, because OPENROWSET does not allow its parameters to be variables (only literals).

My suggestion to you is that you create another variable, let's say [@.sql varchar(255)]. This variable will store the text of the whole OPENROWSET statement. Having this variable all you have to do is execute the newly created statement. Here's the code:

DECLARE @.sql varchar(255)
SELECT @.sql = 'OPENROWSET(BULK ' + @.filename + ', SINGLE_CLOB)'

SELECT @.strXML = x
FROM EXEC(@.sql) AS result(x)

I hope this helps. Let me know how it goes. Ciao.

Monday, March 12, 2012

Passing a list of numbers to a stored procudure, having a size more than 8000 characters

Hi..

I m working on MS SQL Server 2000.

I am trying to pass a list of numbers to a stored procedure to be used with 'IN()' statement.

I was doing something like..

Create Procedure proc

(

@.Items varchar(100) List of numbers

)

AS Begin

Declare @.SQL varchar(8000)

Set @.SQL =

'

Select Query......

Where products IN (' + @.items + ') '

'

Exec (@.SQL)

This stored procedure is working fine, but when i m adding more required stuff to that, the size exceeds 8000, & it gives the error "Invalid operator for data type. Operator equals add, type equals text."

Can any1 please help me out with this ASAP?

In 2000, you can split the list over mulitple parms and then concat them together when you call the sporc like so:

create proc whatever

( @.Items1 varchar(8000),

@.Itmes2 varchar(8000),

...

)

Declare @.SqlStart Varchar(8000),

@.SqlEnd varchar(8000)

set @.SqlStart = '

Select bla

where products in ('

set SqlEnd = ')'

exec (@.sqlStart + @.Items1 + @.Items2 + ... + @.SqlEnd)

That should work although it tedious to split the items on the calling end. Where do the itmes come from, can;t you use a join or something to get at the records you need?

Regards GJ

|||

Change the datatype from Varchar to Text & execute the query directly dont use any variable.

Code Snippet

Create Procedure [Proc]

(@.Items text)

AS

Begin

Exec ('Select Query......

Where products IN (' + @.items + ')')

End

|||

Thanks GJ...

Works fine after splitting the varchar...

I was thinking about using joins as well but I guess its not possible the way my query is.

Anyways... Thanks for ur help both of Us Smile

passing a 'In expression' to Stored procedure

Are there a way to pass a expression as a parameter of a stored procedure?
I am writing a stored procedure,
There is a Select statement something like:
Select Name, Street, City, State from CustomerAddress where state in
('MN','CA','TN')
Are there a way passing "('MN','CA','TN')" as parameter to the stored
Procedure?
ThanksHere is a solution.
Arrays and Lists in SQL Server
http://www.sommarskog.se/arrays-in-sql.html
AMB
"M" wrote:

> Are there a way to pass a expression as a parameter of a stored procedure?
> I am writing a stored procedure,
> There is a Select statement something like:
> Select Name, Street, City, State from CustomerAddress where state in
> ('MN','CA','TN')
> Are there a way passing "('MN','CA','TN')" as parameter to the stored
> Procedure?
> Thanks
>
>|||On Thu, 11 May 2006 11:54:55 -0700, M wrote:

>Are there a way to pass a expression as a parameter of a stored procedure?
>I am writing a stored procedure,
>There is a Select statement something like:
>Select Name, Street, City, State from CustomerAddress where state in
>('MN','CA','TN')
>Are there a way passing "('MN','CA','TN')" as parameter to the stored
>Procedure?
Hi M,
http://www.sommarskog.se/arrays-in-sql.html
Hugo Kornelis, SQL Server MVP

passing a coma delimited group of numbers to a collection for sql

I have a sql statement and one of the arguments I want to pass is a comma delimited set of numbers. It keeps getting turned into a string. How do I keep that from happening. Here is kind of what it looks like
Select FirstName
from User
where NameID in (5,6,7)
or
Select FirstName
from User
where NameID in (@.NameIDList)
There is no error code just nothing returns. If I take out the @.ANameIDList and put the values I want, it returns the correct results.
Thanks,
Bryan
PS the link to the original thread it herehttp://forums.asp.net/1046154/ShowPost.aspxHey,
Right, because unfortunately you can't pass in a list, instead it looks for all the numbers as a string. Instead, you have to create a dynamic string, assign it to a string variable, and do it that way:
declare @.sql varchar(8000)
set @.sql = 'select FirstName from User where NameID in (' + @.NameIDList + ')'
exec(@.sql) -- maybe without parens

Wednesday, March 7, 2012

pass the parameters with more then one insert into statement

We could do this
Insert into tablename (field1, field2) values ('apple','23'), ('organes',
34), etc.
How can we pass the parameters so I can do that in stored procedure?
Thanks.
Grant
Who gives a {censored} if I am wrong.Grant,
Create an xml document and pass it to the stored procedure. See function
"openxml" in BOL for more info.
AMB
"Grant" wrote:

> We could do this
> Insert into tablename (field1, field2) values ('apple','23'), ('organes',
> 34), etc.
>
> How can we pass the parameters so I can do that in stored procedure?
>
> Thanks.
>
> --
> Grant
> Who gives a {censored} if I am wrong.
>
>|||Grant wrote:
> We could do this
> Insert into tablename (field1, field2) values ('apple','23'), ('organes',
> 34), etc.
>
> How can we pass the parameters so I can do that in stored procedure?
>
> Thanks.
>
> --
> Grant
> Who gives a {censored} if I am wrong.
INSERT INTO tablename (col1, col2)
SELECT @.p1, @.p2 UNION ALL
SELECT @.p3, @.p4 UNION ALL
SELECT @.p5, @.p6 ;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||but you cannot do that in SP, right? We will not know how many records will
be inserted.
Grant
Who gives a {censored} if I am wrong.
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:1144093592.580516.164870@.i40g2000cwc.googlegroups.com...
> Grant wrote:
> INSERT INTO tablename (col1, col2)
> SELECT @.p1, @.p2 UNION ALL
> SELECT @.p3, @.p4 UNION ALL
> SELECT @.p5, @.p6 ;
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>|||You could pass the data as a comma separated string, there's a good
article here:
http://www.sommarskog.se/arrays-in-sql.html
that will describe efficient ways to split it back out into a temporary
table, from which you could easily call a multirow insert.|||Grant wrote:
> but you cannot do that in SP, right? We will not know how many records wil
l
> be inserted.
> --
> Grant
You can do it like the following example. I'm assuming Col1 is the key
column here. Procs can have over 2000 optional parameters. If you need
as many as that then I'd consider the XML solution.
CREATE PROC dbo.usp_tablename_insert
(
@.p1 INTEGER = NULL,
@.p2 INTEGER = NULL,
@.p3 INTEGER = NULL,
@.p4 INTEGER = NULL,
@.p5 INTEGER = NULL,
@.p6 INTEGER = NULL
)
AS
BEGIN
INSERT INTO tablename (col1, col2)
SELECT col1, col2
FROM
(SELECT @.p1, @.p2 UNION ALL
SELECT @.p3, @.p4 UNION ALL
SELECT @.p5, @.p6)
AS T(col1, col2)
WHERE col1 IS NOT NULL ;
END ;
RETURN ;
GO
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx|||>> but you cannot do that in SP, right? We will not know how many records [sic] w
ill
be inserted. <<
teh syntax you guessed at in your first posting was Standard SQL, but
SQL Server does not support it yet.
You can have just over 1000 parameters in T-SQL, so you could use
David's suggestion with a really long union of pairs. This code will
port, avoid proprietary XML tricks and dynamic SQL. Do you often have
over 500 rows (NOT records) to insrt?|||One table has up to 20 records and another one up to 30 so I am using David
suggestion. I do have one table that could go over hundred so I may use
openxml method for that one but I may just send out 100 at a time because I
think opensml is not good for performance.
Grant
Who gives a {censored} if I am wrong.
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1144270087.388066.264100@.v46g2000cwv.googlegroups.com...
> be inserted. <<
> teh syntax you guessed at in your first posting was Standard SQL, but
> SQL Server does not support it yet.
> You can have just over 1000 parameters in T-SQL, so you could use
> David's suggestion with a really long union of pairs. This code will
> port, avoid proprietary XML tricks and dynamic SQL. Do you often have
> over 500 rows (NOT records) to insrt?
>

Saturday, February 25, 2012

pass Column Name using Parameter in SQL Statement...

Hi,

I am trying to Pass Column Name(FieldName) using Parameter in SQL
Statement... But i am getting error...

how can i pass Column name using parameter?

Example:

in table i have fieldname ECountry...

Select @.FName='ECountry'
Select @.FName from Table...

How it works?

Thanx in Advance,
Regards,
Raghu...(raghutumma@.gmail.com) writes:

Quote:

Originally Posted by

I am trying to Pass Column Name(FieldName) using Parameter in SQL
Statement... But i am getting error...
>
how can i pass Column name using parameter?
>
Example:
>
in table i have fieldname ECountry...
>
Select @.FName='ECountry'
Select @.FName from Table...
>
How it works?


Why would you do it in the first place? Given a well-designed database,
the request does not make very much sense. But if you have a less well-
designed database, you need to do:

SELECT CASE @.paramname
WHEN 'thatfield' THEN thatfield
WHEN 'thisfield' THEN thisfield
WHEN 'leftfield' THEN leftfield
END
FROM tbl

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||>how can i pass Column name using parameter? <<

You don't do this; it is bad programming. A well-designed module of
code returns a predictable result. What you have is what I call a
"Britney Spears, Squids and Automobiles" module, since it can return
anything of any data type!

Get a book on basic Software Engineering and read about coupling and
cohesion before you do any more programming in any language.|||On Oct 19, 9:06 am, --CELKO-- <jcelko...@.earthlink.netwrote:

Quote:

Originally Posted by

Quote:

Originally Posted by

Quote:

Originally Posted by

how can i pass Column name using parameter? <<


>
You don't do this; it is bad programming. A well-designed module of
code returns a predictable result. What you have is what I call a
"Britney Spears, Squids and Automobiles" module, since it can return
anything of any data type!
>
Get a book on basic Software Engineering and read about coupling and
cohesion before you do any more programming in any language.


Maybe they weren't responsible for the database design, but are being
asked query from it due to business requirements or maybe it's not a
critical application and it's was easier to load a flat file into
Access than to design a proper normalized database. Regardless, it's
a legitimate question (as are your concerns about unpredictable
results), but to assume that Raghu doesn't know basic Software
Engineering is rude.|||<paulschultz54@.gmail.comwrote in message
news:1193191383.235885.139270@.y27g2000pre.googlegr oups.com...

Quote:

Originally Posted by

On Oct 19, 9:06 am, --CELKO-- <jcelko...@.earthlink.netwrote:

Quote:

Originally Posted by

Quote:

Originally Posted by

>how can i pass Column name using parameter? <<


>>
>You don't do this; it is bad programming. A well-designed module of
>code returns a predictable result. What you have is what I call a
>"Britney Spears, Squids and Automobiles" module, since it can return
>anything of any data type!
>>
>Get a book on basic Software Engineering and read about coupling and
>cohesion before you do any more programming in any language.


>
Maybe they weren't responsible for the database design, but are being
asked query from it due to business requirements or maybe it's not a
critical application and it's was easier to load a flat file into
Access than to design a proper normalized database. Regardless, it's
a legitimate question (as are your concerns about unpredictable
results), but to assume that Raghu doesn't know basic Software
Engineering is rude.


You know, Joe has written several books, SQL for Smarties comes to mind.

However, one book that I doubt he'll ever be asked to write is "Joe Celko's
Guide to Winning Friends and Influencing People."

:-)

Quote:

Originally Posted by

>


--
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com http://www.greenms.com/sqlserver.html|||Or... Practical SQL Solutions in the Real World.

--
Tony Rogerson, SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson
[Ramblings from the field from a SQL consultant]
http://sqlserverfaq.com
[UK SQL User Community]

"Greg D. Moore (Strider)" <mooregr_deleteth1s@.greenms.comwrote in message
news:13hubgltianpsb8@.corp.supernews.com...

Quote:

Originally Posted by

<paulschultz54@.gmail.comwrote in message
news:1193191383.235885.139270@.y27g2000pre.googlegr oups.com...

Quote:

Originally Posted by

>On Oct 19, 9:06 am, --CELKO-- <jcelko...@.earthlink.netwrote:

Quote:

Originally Posted by

>>how can i pass Column name using parameter? <<
>>>
>>You don't do this; it is bad programming. A well-designed module of
>>code returns a predictable result. What you have is what I call a
>>"Britney Spears, Squids and Automobiles" module, since it can return
>>anything of any data type!
>>>
>>Get a book on basic Software Engineering and read about coupling and
>>cohesion before you do any more programming in any language.


>>
>Maybe they weren't responsible for the database design, but are being
>asked query from it due to business requirements or maybe it's not a
>critical application and it's was easier to load a flat file into
>Access than to design a proper normalized database. Regardless, it's
>a legitimate question (as are your concerns about unpredictable
>results), but to assume that Raghu doesn't know basic Software
>Engineering is rude.


>
You know, Joe has written several books, SQL for Smarties comes to mind.
>
However, one book that I doubt he'll ever be asked to write is "Joe
Celko's Guide to Winning Friends and Influencing People."
>
:-)
>
>

Quote:

Originally Posted by

>>


>
>
>
--
Greg Moore
SQL Server DBA Consulting Remote and Onsite available!
Email: sql (at) greenms.com
http://www.greenms.com/sqlserver.html
>
>

Pass a variable to SET IDENTITY_INSERT

I'm quite new to programming with SQL Server.
I'm developing an SQL statement using Query Analyzer that read a table from a MSAccess Linked server database, and put the data in to a SQL server table.

I'd like that table name, db name, etc, are values stored in some variables, so, when i want to import another table, i need to change only the value of the @.table_name variable.

I can pass the value of this variable to all the statements of my script but one. I'm able to execute something like

EXEC ('select * from' + @.table_name + '... bla bla bla')

but i'm not able to execute the SET IDENTITY_INSERT @.table_name ON/OFF.
I tried many options like print, exec, quotes, double quotes, etc, but nothing to do.

I'd really appreciate all your helping answers.

Ciao

Darioif you wish to do this you will need to build a string containing the set statement and the insert statment. then EXEC(@.string).

Remember that EXEC() runs on a seperate thread than your current connection so any settings will be lost once the EXEC finishes.

declare @.TSQL varchar(1000)
CREATE TABLE #products (id int IDENTITY PRIMARY KEY, product varchar(40))

-- Inserting values into products table.
INSERT INTO #products (product) VALUES ('screwdriver')
INSERT INTO #products (product) VALUES ('hammer')

select * From #Products

-- Inserting ids and values into products table.
set @.TSQL = 'set identity_insert #products on
INSERT INTO #products (id,product) VALUES (10,''saw'')
INSERT INTO #products (id,product) VALUES (11,''shovel'')'

exec(@.TSQL)

select * from #products

drop table #Products|||The script is the following:

-- Variable declaration
DECLARE @.nome_db nvarchar(50)
DECLARE @.nome_tabella nvarchar(50)
DECLARE @.id_tabella int
DECLARE @.str_nome_campi nvarchar(255)
DECLARE @.str_tmp_nome_campo nvarchar(255)
DECLARE @.strdata nvarchar(255)
DECLARE @.str_sql nvarchar(255)
DECLARE @.str_sql_delete nvarchar(255)
DECLARE @.str_sql_use nvarchar(255)
DECLARE @.str_sql_debug nvarchar(255)
DECLARE @.str_id_insert_on nvarchar(50)
DECLARE @.str_id_insert_off nvarchar(50)

-- Set the variables
SET @.nome_db = 'Unitec_Script_Importazione'
SET @.nome_tabella = 'ANFRAGEDETAILS2'

SET @.str_sql_delete = 'DELETE FROM [' + @.nome_db + '].[dbo].[' + @.nome_tabella + ']'
SET @.str_sql_use ='USE [' + @.nome_db + ']'
SET @.str_sql_debug = 'SELECT TOP 10 * FROM ' + @.nome_tabella

-- Stringhe per settare Identity ... maledette!
SET @.str_id_insert_on = ' SET IDENTITY_INSERT ' + quotename(@.nome_tabella) + ' ON' + char(10)
SET @.str_id_insert_off =' SET IDENTITY_INSERT ' + quotename(@.nome_tabella) + ' OFF' + char(10)
-- Trovo, all'interno della tabella di sistema sysobjects, l'ID
-- della tabella. Usando questo valore posso trovare i campi relativi
SET @.id_tabella = (SELECT [id] FROM sysobjects WHERE [name] LIKE @.nome_tabella)
--SELECT @.id_tabella -- (debug - stampa il risultato della query)

DECLARE nome_campi CURSOR
FOR SELECT [name] FROM syscolumns where id = @.id_tabella
-- Open the cursor
OPEN nome_campi
-- Prendo la prima riga del cursore e la schiaffo dentro alla variabile temporanea
FETCH NEXT FROM nome_campi INTO @.str_tmp_nome_campo

SET CONCAT_NULL_YIELDS_NULL OFF

WHILE @.@.FETCH_STATUS = 0
BEGIN
SET @.str_nome_campi = @.str_tmp_nome_campo
SET @.strdata = @.str_nome_campi + @.strdata
FETCH NEXT FROM nome_campi INTO @.str_tmp_nome_campo
-- Aggiungo la virgola se necessario
SET @.str_tmp_nome_campo = @.str_tmp_nome_campo + ', '
END

SELECT @.strdata -- Debug: stampa il contenuto di strdata

CLOSE nome_campi
DEALLOCATE nome_campi

EXECUTE (@.str_sql_use)

EXECUTE sp_executesql @.str_sql_delete

/******* THIS IS WHERE I NEED HELP*********
Instead of the name of the table (ANFRAGEDETAILS2)
i want to use a variable @.table_name
*****************************************/
SET IDENTITY_INSERT ANFRAGEDETAILS2 ON

SET @.str_sql = @.str_sql + 'INSERT INTO [dbo].[' + @.nome_tabella + '] (' + @.strdata + ') SELECT * FROM OPENQUERY(Anfragen, ''Select ' + @.strdata + ' from [' + @.nome_tabella + ']'')'

EXECUTE (@.str_sql)

SET IDENTITY_INSERT ANFRAGEDETAILS2 OFF

--
--
--|||have you tried:

SET @.str_sql = @.str_sql + 'SET IDENTITY_INSERT ANFRAGEDETAILS2 ON
INSERT INTO [dbo].[' + @.nome_tabella + '] (' + @.strdata + ') SELECT * FROM OPENQUERY(Anfragen, ''Select ' + @.strdata + ' from [' + @.nome_tabella + ']'')
SET IDENTITY_INSERT ANFRAGEDETAILS2 OFF'
EXECUTE (@.str_sql)|||Yes, 'SET IDENTITY_INSERT ANFRAGEDETAILS2 ON ... works
but 'SET IDENTITY_INSERT @.table_name ON ... Doesn't work|||AND
SET @.str_sql = @.str_sql
+ ' SET IDENTITY_INSERT [dbo].['+@.nome_tabella+'] ON '
+'INSERT INTO [dbo].[' + @.nome_tabella + '] (' + @.strdata + ') SELECT * FROM OPENQUERY(Anfragen, ''Select '' + @.strdata + '' from ['' + @.nome_tabella + '']'')'
EXECUTE (@.str_sql)
WORKS !?|||Yes, it works!!!

Many thanks

Dario

Pass a variable to a linked server (FoxPro) query

I'm having problem with an OpenQuery statement in stored procedure, which should be run on FoxPro linked server. I'm getting either an error messages or not the result I expected. I know that the problem is with WHERE part, without this part it works.

Here is the code:
------------
DECLARE @.LastDate datetime
SELECT @.LastDate = MAX(DateChaged)
FROM tblPersonel
WHERE ACTIVE IN( 'A', 'T')

1. I tried:
SELECT * FROM OPENQUERY(FoxProLink, 'SELECT ACTIVE, EmpNumber FROM tblPersonel WHERE DateChanged >=''+@.LastDate+''')

This line gives me an error msg:

Could not execute query against OLE DB provider 'MSDASQL'.
[OLE/DB provider returned message: [Microsoft][ODBC Visual FoxPro Driver]Operator/operand type mismatch.]

2. I tried to use CTOD() - FOXPRO function to convert character to date.

SELECT * FROM OPENQUERY(FoxProLink, 'SELECT ACTIVE, EmpNumber FROM tblPersonel WHERE DateChanged >=CTOD(''+@.LastDate+'')')

-this doesn't give any error, but doesn't limit the result set as it should.

Thanks all.I am surprised that #2 works, because OPENQUERY does not work with parameter parsing or dynamic SQL tricks that SQL lets you get away with.|||I read an article on MSDN, describing how to pass a variable to linked server query...at the same time I read elsewhere that you can not pass parametrs to OpenQuery...
Does anybody have any suggestions?
Thanks all.