Showing posts with label sysname. Show all posts
Showing posts with label sysname. Show all posts

Sunday, February 19, 2012

Dynamic SQL to populate a variable

Here's the WRONG way to do what I want. I need a way to populate a variable from the output of a dynamic query.

declare @.TableName sysname

set @.TableName = 'Customers'

delcare @.Output bigint

declare @.SQL varchar(max)

set @.SQL = 'select top 1 RowID from ' + @.TableName

select @.Output =

EXEC (@.SQL)

create function udf_GetDatabaseFingerPrint(

@.DBID bigint

)

begin

returns bigint

as

declare @.dbname sysname

, @.iBig bigint

, @.tSQL varchar(2000)

select @.dbName = Name from Master.Dbo.Sysdatabases where DBID = @.DBID

set @.tSQL = 'select sum(Rows) from ' + @.dbName + '.dbo.sysindexes'

set @.iBig = exec(@.tSQL)

return @.iBig

end

Number one, you cannot do this in a T-SQL function. Functions will not allow such things. You can use sp_executeSQL. In this case, something like this (and old example I hadSmile

declare @.objectId int,

exec sp_executeSQL

N'select @.objectId = max(object_id) from sys.objects',

N'@.objectId int output', @.objectId=@.objectId output

select @.objectId

Wednesday, February 15, 2012

Dynamic SQL Help needed.

I have the following stored procedure :

CREATE PROCEDURE usp_CraneRental_UpdateRate
@.iEntryID int,
@.cField sysname,
@.cValue varchar(100),
@.dtModified datetime OUTPUT

AS

SELECT @.dtModified = GetDate()

DECLARE @.cSql VARCHAR(500)

SELECT @.cSql = 'UPDATE tbCraneRentalRates SET ' + @.cField + ' = ' + RTRIM(@.cValue) +
', Modified = ' + '"' + CAST(@.dtModified AS VARCHAR) + '"' +
' WHERE EntryID = ' + CAST(@.iEntryID AS VARCHAR)

EXEC(@.cSql)
IF(@.@.ERROR <> 0 OR @.@.ROWCOUNT <= 0)
RAISERROR('Failed to update transportation rate!',16,1)
GO

that generates the following SQL String :

UPDATE tbCraneRentalRates SET MoveIn = 0, Modified = "May 20 2004 9:59 AM" WHERE EntryID = 1

The error I am getting is:

Server: Msg 207, Level 16, State 3, Line 1
Invalid column name 'May 20 2004 9:59AM'.

???
This doesn't make sence, the SQL statement looks perfectly fine ?

Any help?
Mike Btry using 2 ' quotes to make it create ', youre giving it the text in speach " " marks which sql doesn't like.

try '' should make it display '|||put this before the create statement in qa:

set quoted_identifiers off|||try using 2 ' quotes to make it create ', youre giving it the text in speach " " marks which sql doesn't like.

try '' should make it display '

That works, thanks.

Mike B