Showing posts with label varchar. Show all posts
Showing posts with label varchar. Show all posts

Tuesday, March 27, 2012

Dynamic query: EXEC - Need to get a return value from query

I use dynamic SELECT statement trying to achive the followng:

DECLARE @.table varchar(50)

DECLARE @.ColumnA varchar(50)

DECLARE @.Result float

SET @.table = 'TABLE_A'

SET @.ColumnA = 'COLUMN_1'

SET @.SQL = ' SELECT @.Result = (SUM((' + @.ColumnA + ' )) FROM ' + @.table

EXEC (@.SQL)

I need to assign the outcome of this statement to the @.Result variable. It does not work because of different contexts for @.Result. It would run if I do

SET @.SQL = 'DECLARE @.Result float '

SET @.SQL = @.SQL + ' SELECT @.Result = (SUM((' + @.ColumnA + ' )) FROM ' + @.table

But in this case @.Result is not 'visible' outside EXEC statement.

One way to solve this is to use INSERT statement into temp table and then read result from the temp table.

Are there any more elegant solutions?

Thanks!

Sorry, but the code in EXEC() is considered to be its own batch, so you will need to persist it in a table, and temp tables are usually used for this. BTW, what did you need to do with the @.Result value? You may be able to put that in the same EXEC() code.

Thanks, Dean

|||

There are different ways to execute dynamic sql. The one that you need is sp_execsql. It allows you to declare parameters -- even output parameters. A key to remember is that an output parameter must be declared as output twice, in much the same way that an output parameter is declared both inside a stored procedure and on the exec line.

Your code should look like:

Declare @.result float

SET @.SQL = @.SQL + ' SELECT @.Result = (SUM((' + @.ColumnA + ' )) FROM ' + @.table

exec sp_execsql @.sql, N' @.Result float Output', @.Result output

The command wants NVarchar() parameters. Make sure @.sql is declared NVarchar() and include the N on the literal declaring the parameter. You can have multiple parameters if needed.

Monday, March 26, 2012

Dynamic Query

Hi friends,
this my query
declare @.i_errorDb varchar(200)
declare @.i_tableName varchar(200)
Declare @.SQL varchar(4000)
Declare @.ParamList varchar(4000)
select @.i_errorDb = 'test'
select @.i_tableName = 'employee'
select @.SQL = 'if exists (select * from @.xi_errorDb.dbo.sysobjects where id
= object_id([dbo].[@.xi_tableName]) and OBJECTPROPERTY(id, IsUserTable) = 1) '
select @.paramlist = '@.xi_errorDb varchar(200),
@.xi_tableName varchar(200)'
sp_executesql @.sql,@.paramlist,@.i_errorDb,@.i_tableName
I am getting syntax error. Please help me to solve this.
thanks
vanithaShould be something like this:
select @.SQL = 'if exists (select * from ' + @.xi_errorDb +
'.dbo.sysobjects where id
= object_id([dbo].[' + @.xi_tableName + ']) and OBJECTPROPERTY(id,
IsUserTable) = 1)'
sp_executesql @.sql
But suggestable to use the INFORMATION_SCHEMA Views:
select @.SQL = 'if exists (select * from ' + @.xi_errorDb +
'.INFORMATION_SCHEMA.TABLES ' +
'Table_Name like ' + CHAR(39) + @.xi_tableName +
CHAR(39)
sp_executesql @.sql
HTH, Jens Suessmeyer.|||still i am getting the same error
"Jens" wrote:

> Should be something like this:
> select @.SQL = 'if exists (select * from ' + @.xi_errorDb +
> '.dbo.sysobjects where id
> = object_id([dbo].[' + @.xi_tableName + ']) and OBJECTPROPERTY(id,
> IsUserTable) = 1)'
> sp_executesql @.sql
> But suggestable to use the INFORMATION_SCHEMA Views:
>
> select @.SQL = 'if exists (select * from ' + @.xi_errorDb +
> '.INFORMATION_SCHEMA.TABLES ' +
> 'Table_Name like ' + CHAR(39) + @.xi_tableName +
> CHAR(39)
> sp_executesql @.sql
>
> HTH, Jens Suessmeyer.
>|||Could you please post the error ? The best thing would be also to Print
out the produced SQL with Print @.Sql before executing it.
Jens Suessmeyer.|||when the query is printed and executed its executing, but with sp_executesql
its throwing "syntax error near sp_executesql"
declare @.i_errorDb varchar(200)
declare @.i_tableName varchar(200)
Declare @.SQL varchar(4000)
Declare @.ParamList varchar(4000)
select @.i_errorDb = 'test'
select @.i_tableName = 'employee'
select @.SQL = 'if exists (select * from ' + @.i_errorDb +
'.INFORMATION_SCHEMA.TABLES where ' +
'Table_Name like ' + CHAR(39) + @.i_tableName +
CHAR(39) + ') drop table ' + @.i_errorDb + '.dbo.'+@.i_tableName
print @.sql
sp_executesql @.sql
"Jens" wrote:

> Could you please post the error ? The best thing would be also to Print
> out the produced SQL with Print @.Sql before executing it.
> Jens Suessmeyer.
>|||You have to EXEC the stored procedure if you are having just once batch
use habe to split the batch via GO to execute a procedure without the
word EXEC or you place an execute (whch shoudl be the prefered method)
in front of the procedurename, or you use another syntax with just the
EXEC word (sp_executesql required an nvarchar, so you want to use this
further you have to change the @.sql variable to nvarchar)
declare @.i_errorDb varchar(200)
declare @.i_tableName varchar(200)
Declare @.SQL varchar(4000)
Declare @.ParamList varchar(4000)
select @.i_errorDb = 'test'
select @.i_tableName = 'employee'
select @.SQL = 'if exists (select * from ' + @.i_errorDb +
'.INFORMATION_SCHEMA.TABLES where ' +
'Table_Name like ' + CHAR(39) + @.i_tableName +
CHAR(39) + ') drop table ' + @.i_errorDb + '.dbo.'+@.i_tableName
print @.sql
EXEC(@.SQL)
--OR
--EXEC sp_executesql @.sql
HTH, jens Suessmeyer.

Thursday, March 22, 2012

Dynamic order by and JOIN

Hi,
Here is my code:
ALTER PROCEDURE dbo.sp_GetPeopleDetails_1
@.OrderByClause varchar(100)
AS
DECLARE @.SQLStatement varchar(255)
SELECT @.SQLStatement = 'SELECT People.PeopleID, People.FirstLastName, People.Title,
Departments.AcademicArea, Shifts.ShiftName, People.TShirt,
People.ParkingFROM Departments INNER JOIN
People ONDepartments.DepartmentID = People.DepartmentID
INNER JOINShifts ON People.ShiftID = Shifts.ShiftID
order By ' +@.OrderByClause
EXEC(@.SQLStatement)
/* SET NOCOUNT ON */
RETURN
When I run it, the error is: "Incorrect syntax near the keyword 'IN'."
Can anyone point my mistake?
Thanks.

Could the 'IN' be in the @.OrderByClause text?

Brian

|||Does this happen with any orderbyclause or just a particular one?|||

run the query in the Query analyzer passing the order by clause and do a PRINT(@.SQLStatement) to see how its building up.

On another note you should not be prefixing your stored proc with "SP_". It causes performance degradation as the sql server will first look under master database assuming its a system proc and then not finding there will look under the database you ware working with.

|||

Finally, problem solved, when I run it in Query analyzer itshowed a truncated query, very strange as I have had it set to varchar(255). Ijust increased it to 500 even though the query does not have more 255characters.
Thanks for the tip with the sp_

Wednesday, March 21, 2012

Dynamic name of result column in s-proc?

How can I make this stored procedure concept work:

---------------
Create Procedure MyProc @.MyValue varchar(5)
As
Declare @.ColumnName as varchar(11)
Set @.ColumnName = 'Price_' + @.MyValue
Select Sum(Price) As @.ColumnName --??
From MyTable where Item = @.MyValue
Return
---------------

Using @.MyValue = 23 should make the Sum(Price) column name 'Price_23'. It's not working. What am I doing wrong?

BjornUSE Northwind
GO

DECLARE @.ColumnName sysname, @.sql varchar(8000), @.myValue varchar(5)
SELECT @.myValue = '23'
SET @.ColumnName = 'Price_' + @.MyValue
SELECT @.sql = 'SELECT Sum(UnitPrice) As ' + @.ColumnName
+ ' FROM [Order Details] '
+ ' WHERE ProductID = ' + @.MyValue

SELECT @.sql

EXEC(@.sql)|||Thank you thank you!

Bjornsql

Sunday, March 11, 2012

Dynamic filedlength of varchar fields in source

I'm using SSIS to import data from a table (SQL) containing varchar fields. The problem is, that those varchar fields are changing over time (sometimes shrinking and sometimes expanding). I.e. from varchar(16) to varchar(20).

When I create my SSIS package, the package seem to store information about the length of each source-field. At runtime, if the field-length is larger then what the package expects an error is thown.

Is there anyway around this problem?

Oh, yeah... My destination fields are a lot wider then the source fields, so the problem is not that the varchar values doesn't fit in my destination table, but that the package expects the source to be smaller...

Regards Andreas

You cannot dynamically change the metadata in an SSIS package -- it needs to be fixed at design time.

You could try casting the source fields to the size they will be on the destination, and hope that the source fields never exceed this size. Or, you could castthe source fields to DT_TEXT so that length can be variable, but performance might suffer (there is extra processing going on for long-object types like DT_TEXT).

Thanks
Mak

|||

A. Brosten wrote:

I'm using SSIS to import data from a table (SQL) containing varchar fields. The problem is, that those varchar fields are changing over time (sometimes shrinking and sometimes expanding). I.e. from varchar(16) to varchar(20).

When I create my SSIS package, the package seem to store information about the length of each source-field. At runtime, if the field-length is larger then what the package expects an error is thown.

Is there anyway around this problem?

Oh, yeah... My destination fields are a lot wider then the source fields, so the problem is not that the varchar values doesn't fit in my destination table, but that the package expects the source to be smaller...

Regards Andreas

You can change the SSIS package so that the external metadata stored within there is large enough for all eventualities.

-Jamie

Friday, March 9, 2012

dynamic evaluation of expression operator (was "Substitution")

Hi I am trying to do something like the following:

DECLARE @.Operator varchar(1)
DECLARE @.Rate float
DECLARE @.Quantity float
DECLARE @.Converted float

SET @.Quantity = 6
SET @.Operator = '/'
SET @.Rate = 2
SET @.Converted = 0

@.Converted = (@.Quantity substituteTheValueOfThis(@.Operator) @.Rate)

PRINT @.Converted

so that the output would be 3

The reason I need to do it like this is that @.Operator will change at runtime...

Any suggestions appreciated, I have looked at EXEC sp_execsql but somehow can't get the syntax right.First of all, the following

DECLARE @.Operator varchar(1)
DECLARE @.Rate float
DECLARE @.Quantity float
DECLARE @.Converted float

SET @.Quantity = 6
SET @.Operator = '/'
SET @.Rate = 2
SET @.Converted = 0

Could be shortened to

DECLARE
@.Operator varchar(1)
, @.Rate float
, @.Quantity float
, @.Converted float
, @.cmd varchar(1000)

select @.Quantity = 6, @.Operator = '/', @.Rate = 2, @.Converted = 0
set @.cmd = 'select convert(decimal(38, 2), ' + convert(varchar, @.Quantity) + convert(Varchar,@.Operator) + convert(varchar, @.Rate) + ')'
exec (@.Cmd)

Sorry about the poor formatting, but this is cut n' pasted directly from Query Analyzer.

Generally when you do calculations in SQL Server, your result will be with or without decimals depending on whether you supply decimals to the calculation at hand, hence
3/2=1
3.0/2=1.500000|||Thanks, this seems to work great when:

select @.Quantity = 6, @.Operator = '/', @.Rate = 2, @.Converted = 0

but returns 0 when

select @.Quantity = 6, @.Operator = '/', @.Rate = 100, @.Converted = 0

rather than

.06

Ah!! Is this what you mean at the end of your post by...

"Generally when you do calculations in SQL Server, your result will be with or without decimals depending on whether you supply decimals to the calculation at hand, hence
3/2=1
3.0/2=1.500000"

I am trying to do conversions between grams and kilograms to 3dp.. so values maybe something like...

34.876 grams and i need to convert that to kilograms so would

0.034876 which I would probably round to 0.035 kilograms

This works but also value maybe

6 grams to kilograms which at the moment returns 0

Thanks for tips on the code and for making the title to thread more appropriate, I still have a lot to learn about transact sql and using this forum... :)|||Sorry I forgot, can I also assign the result of the EXEC statement to a variable like this...

@.Result = EXEC (@.cmd)

I know this doesn't work but it illustrates what I am hoping to do!

Thanks again!!!|||Yes it IS possible to write dynamic SQL in a way that makes the execution of the string return a value (do a search on the words "dynamic SQL OUTPUT" on these boards and you'll find quite a few posts about it.
However, dynamic SQL is not optimized by SQL Server (and couldn't be since it's not decided what it looks like until runtime.) and therefore it can be quite slow. If I understand your post correctly, basically what you are going for is a "mini-calculator"-procedure. You wanna send a first parameter, a operator and another operator to a procedure, and then do the evaluation and return the results in a proc.

If that is the case, you could probably get away with
-- Start proc
create procedure test as
@.Param1 float,
@.Param2 float,
@.Operator char(1)

as

select
case @.Operator
when '-' then @.Param1 - @.Param2
when '+' then @.Param1 + @.Param2
when '*' then @.Param1 * @.Param2
when '/' then @.Param1 / @.Param2
else
-1
end
return
-- End proc
However I cannot see how this is needed, since the calculation should probably be done in the client. (Given that this procedure is in a serverside solution, which I assumed that it is ...)
No need to do the dynamic SQL there. Perhaps I've simplified your problem and not considered all other factors, but as far as I can see my solution could work nicely, from a SQL point of view, but probably not from a architectual point of view. However, I choose not to discuss those matters here.

Good luck. :cool:|||Thank you very very much! You've set me thinking about the placing of this routine and maybe as you say, it should really be in the middle tier.

Thanks again for your time and very helpful comments

Cheers :)

Wednesday, March 7, 2012

Dynamic database problem!

I use the following query to enable a dynamic database in my reportviewer.
declare @.SQL varchar(255)
select @.SQL = 'select * from ' + @.DBName + '.dbo.V_RoofSection Where
(Section =' + @.Section + ') and (bassin =' + @.Bassin + ')'
exec (@.SQL)
This query causes a problem though.
Since the query is exacuted as a string, the resultset columns are not
recognized by the compiler and several errors appear when i try to preview my
report.
Is there a way to explicitely specify my columns on the above query so they
are recognized by the builder? Something like:
SELECT Section, Bassin FROM exec(@.SQL)
I hope i am clear enough.You should still be able to get the field list. Have you tried the refresh
fields button (to the right of the ...)
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"Eric" <Eric@.discussions.microsoft.com> wrote in message
news:8E1215FA-815A-4F99-9D29-B1D0F51C0415@.microsoft.com...
>I use the following query to enable a dynamic database in my reportviewer.
> declare @.SQL varchar(255)
> select @.SQL = 'select * from ' + @.DBName + '.dbo.V_RoofSection Where
> (Section =' + @.Section + ') and (bassin =' + @.Bassin + ')'
> exec (@.SQL)
> This query causes a problem though.
> Since the query is exacuted as a string, the resultset columns are not
> recognized by the compiler and several errors appear when i try to preview
> my
> report.
> Is there a way to explicitely specify my columns on the above query so
> they
> are recognized by the builder? Something like:
> SELECT Section, Bassin FROM exec(@.SQL)
>
> I hope i am clear enough.
>|||Yes I get them now ... I cant believe it was that simple. :)
"Bruce L-C [MVP]" wrote:
> You should still be able to get the field list. Have you tried the refresh
> fields button (to the right of the ...)
>
> --
> Bruce Loehle-Conger
> MVP SQL Server Reporting Services
> "Eric" <Eric@.discussions.microsoft.com> wrote in message
> news:8E1215FA-815A-4F99-9D29-B1D0F51C0415@.microsoft.com...
> >I use the following query to enable a dynamic database in my reportviewer.
> >
> > declare @.SQL varchar(255)
> > select @.SQL = 'select * from ' + @.DBName + '.dbo.V_RoofSection Where
> > (Section =' + @.Section + ') and (bassin =' + @.Bassin + ')'
> > exec (@.SQL)
> >
> > This query causes a problem though.
> >
> > Since the query is exacuted as a string, the resultset columns are not
> > recognized by the compiler and several errors appear when i try to preview
> > my
> > report.
> >
> > Is there a way to explicitely specify my columns on the above query so
> > they
> > are recognized by the builder? Something like:
> >
> > SELECT Section, Bassin FROM exec(@.SQL)
> >
> >
> > I hope i am clear enough.
> >
> >
>
>|||I still have a problem though, there is an error message saying that the
value I give to @.Section is an invalid column name.
declare @.SQL varchar(255)
select @.SQL = 'select distinct bassin from ' + @.DBName + '.dbo.V_RoofSection
Where (Section =' + @.Section + ') and bassin is not null'
exec (@.SQL)
However when I put quotes around my @.Section value the query works. How can
I modify my above query so I don't have to enter quotes around the values I
enter?|||Ok I found it, I just had to replace my single quotes with a triple quote!
god that is intuitive :p
"Eric" wrote:
> I still have a problem though, there is an error message saying that the
> value I give to @.Section is an invalid column name.
> declare @.SQL varchar(255)
> select @.SQL = 'select distinct bassin from ' + @.DBName + '.dbo.V_RoofSection
> Where (Section =' + @.Section + ') and bassin is not null'
> exec (@.SQL)
> However when I put quotes around my @.Section value the query works. How can
> I modify my above query so I don't have to enter quotes around the values I
> enter?

Sunday, February 26, 2012

Dynamic credentials ...

Hi managed to have a dynamic database with SQL server using something like
this as my query :
declare @.SQL varchar(255)
Select @.OwnerID = '[' + @.OwnerID + ']'
select @.SQL = @.DBName + '.dbo.sp_rptFinance ' + @.YearBegin + ',' + @.OwnerID
exec (@.SQL)
However each of my database uses a different set of credentials ... is there
a way to specify the credentials in such a query?
Thx
EricNo, there is not...
credentials are supplied with the connection and are part of the data
source...
--
Wayne Snyder MCDBA, SQL Server MVP
Mariner, Charlotte, NC
(Please respond only to the newsgroup.)
I support the Professional Association for SQL Server ( PASS) and it's
community of SQL Professionals.
"Eric" <Eric@.discussions.microsoft.com> wrote in message
news:572D7F3D-1CCD-4334-86F0-DCF86EE841C8@.microsoft.com...
> Hi managed to have a dynamic database with SQL server using something like
> this as my query :
>
> declare @.SQL varchar(255)
> Select @.OwnerID = '[' + @.OwnerID + ']'
> select @.SQL = @.DBName + '.dbo.sp_rptFinance ' + @.YearBegin + ',' +
> @.OwnerID
> exec (@.SQL)
> However each of my database uses a different set of credentials ... is
> there
> a way to specify the credentials in such a query?
> Thx
> Eric

Sunday, February 19, 2012

Dynamic Column Naming

Greetings,
Very simple question, how do i assign a column same name as its value?
declare @.seas varchar(5) set @.seas = 'Donie'
SELECT @.seas as (')
NOT static please, dynamic. So, SELECT @.seas as 'Donie' won't do me any
good.
Much obliged,
Don
*** Sent via Developersdex http://www.examnotes.net ***don larry wrote:
> Greetings,
> Very simple question, how do i assign a column same name as its value?
> declare @.seas varchar(5) set @.seas = 'Donie'
> SELECT @.seas as (')
> NOT static please, dynamic. So, SELECT @.seas as 'Donie' won't do me
> any good.
> Much obliged,
> Don
>
>
> *** Sent via Developersdex http://www.examnotes.net ***
You need to use dynamic sql, which has security implications if you are
using stored procedures.
For example:
declare @.seas varchar(5)
declare @.sql nvarchar(1000)
set @.seas = 'Donie'
set @.sql = N'SELECT [' + @.seas + N'] from dbo.mytable'
Exec sp_executesql @.sql
David Gugick
Imceda Software
www.imceda.com|||The first obvious question would be "Why would you want to do this?"
Assuming there was some reason, you have to use dynamic SQL to get this kind
of
dynamic feature.
Declare @.Sql VarChar(8000)
Declare @.Seas VarChar(5)
Set @.Sql= 'Select ' + QuoteName(@.Seas, '''') + ' As ' + QuoteName(@.Seas)
Exec(@.Sql)
Thomas
"don larry" <donlarry17@.hotmail.com> wrote in message
news:%23mwQMTAXFHA.2776@.TK2MSFTNGP12.phx.gbl...
> Greetings,
> Very simple question, how do i assign a column same name as its value?
> declare @.seas varchar(5) set @.seas = 'Donie'
> SELECT @.seas as (')
> NOT static please, dynamic. So, SELECT @.seas as 'Donie' won't do me any
> good.
> Much obliged,
> Don
>
>
> *** Sent via Developersdex http://www.examnotes.net ***|||>> how do i assign a column same name as its value? <<
Okay, you missed the whole idea of data modeling, RDBMS, and just about
everything else for the past 35 years in the field. Not a minor
misunderstanding, but all of it at the foundation level. Entities,
attributes and values are TOTALLY DIFFERENT! This is like being in a
math newsgroup and having someone ask "Can I make 2+2=5 If I have
really large values of 2?"
Really bad SQL programmers can use proprietary, dynamic code to kludge
things like this. But if you actually want to be competent, get a good
book on RDBMS and data model, read it and stop programming until you
understand what you are doing.