Please could someone help me understand, why when I run the below SQL code it returns an "s". But when I run the SQL portion on its own it returns the correct value "DaisyRates_May2014"
Full code:
DECLARE @tablevalue varchar
SET @tablevalue = 'select distinct [BillingReferenceData].[dbo].[Customers].[Tariff]
from [daisybilling].[dbo].[APRW14_FFA68878_Calls]
inner join [BillingReferenceData].[dbo].[Customers] on [DaisyBilling].[dbo].[APRW14_FFA68878_Calls].[Customer Lookup] = [BillingReferenceData].[dbo].[Customers].[Customer ID]
where [DaisyBilling].[dbo].[APRW14_FFA68878_Calls].[Customer Lookup] = [BillingReferenceData].[dbo].[Customers].[Customer ID]'
Select @tablevalue
SQL on its own:
'select distinct [BillingReferenceData].[dbo].[Customers].[Tariff]
from [daisybilling].[dbo].[APRW14_FFA68878_Calls]
inner join [BillingReferenceData].[dbo].[Customers] on [DaisyBilling].[dbo].[APRW14_FFA68878_Calls].[Customer Lookup] = [BillingReferenceData].[dbo].[Customers].[Customer ID]
where [DaisyBilling].[dbo].[APRW14_FFA68878_Calls].[Customer Lookup] = [BillingReferenceData].[dbo].[Customers].[Customer ID]
Thanks
You are returning an s
because you are returning the first character of the sql string since you haven't defined a length of your variable. Try using varchar(max)
instead of varchar
.
However, that will just return your sql statement, not run it. I think you want to actually run your sql statement, in which case, you can use exec
or sp_executesql
.
DECLARE @tablevalue varchar(max)
SET @tablevalue = 'select distinct [BillingReferenceData].[dbo].[Customers].[Tariff]
from [daisybilling].[dbo].[APRW14_FFA68878_Calls]
inner join [BillingReferenceData].[dbo].[Customers] on [DaisyBilling].[dbo].[APRW14_FFA68878_Calls].[Customer Lookup] = [BillingReferenceData].[dbo].[Customers].[Customer ID]
where [DaisyBilling].[dbo].[APRW14_FFA68878_Calls].[Customer Lookup] = [BillingReferenceData].[dbo].[Customers].[Customer ID]'
exec(@tablevalue)
You are specifying the the type of @tablevalue is a varchar of length one. Try
DECLARE @tablevalue VARCHAR(MAX)
From http://msdn.microsoft.com/en-us/library/ms176089.aspx
When n is not specified in a data definition or variable declaration statement, the default length is 1
To execute to SQL:
EXEC SP_EXECUTESQL(@tablevalue )
or
EXEC(@tablevalue)
Take a look at http://www.sommarskog.se/dynamic_sql.html to learn about the differences between EXEC and AP_EXECUTESQL.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.