I have a big stored procedure, with some nested cursors fetching some parameters dynamically. In this part I get the problem:
DECLARE #Avg_Dev float;
SET #sqlstatement = 'SELECT #Avg_Dev = AVG([' + #QLabel + '])
FROM Imported_Data
WHERE BrandID = ''' + CAST(#BrandID AS nvarchar(max)) + ''' AND CountryID = ''' + CAST(#CountryID AS nvarchar(max))
+ ''' AND [Year] = ''' + CAST(#Year AS nvarchar(max))
+ ''' AND ' + CAST(#QLabel AS nvarchar(max)) + ' <> ''' + CAST(#NoAnswer AS nvarchar(max)) + ''' ' + #Query;
EXEC sp_executesql #sqlstatement, N'#Avg_Dev float output', #Avg_Dev output;
PRINT 'AVG Check'; PRINT #Avg_Dev;
#BrandID and #CountryID are GUID, #Year is int, #QLabel is int and #Query is nvarchar(max). #NoAnswer contains a special value that has not to be considered.
#QLabel contains the column that I'm processing.
#Query contains a condition to apply to the where statement, and it's different for every #QLabel.
The problem is that #Avg_Dev always contains values rounded to the nearest integer, and I can't see why. #QLabel can be a value between 1 and 10.
I know this is not easy to read, but I didn't find any other way to process the table dynamically with every parameter changing often.
The problem here is that the column (QLabel) is defined as an integer. So an AVG() would return an integer (ignoring the decimals) and pushing that into your float variable. Try this:
SET #sqlstatement = 'SELECT #Avg_Dev = AVG(convert(float,[' + #QLabel + ']))
FROM Imported_Data
WHERE BrandID = ''' + CAST(#BrandID AS nvarchar(max)) + ''' AND CountryID = ''' + CAST(#CountryID AS nvarchar(max))
+ ''' AND [Year] = ''' + CAST(#Year AS nvarchar(max))
+ ''' AND ' + CAST(#QLabel AS nvarchar(max)) + ' <> ''' + CAST(#NoAnswer AS nvarchar(max)) + ''' ' + #Query;
Related
Im trying to use a stored procedure to create a pivot table between two declared variables #rvar (as rowvariable) and #cvar (as columnvariable). The point is to call the stored procedure from VBA using these two as dynamic input when executing the stored procedure.
My code has three parts:
creating test-data
declaring locals
finding names of columns in crosstab an storing in new local #sql1
executing crosstable with the pivotfunction using the names stored in #sql1.
My problem: The code below works but I would like to make it dynamic regarding the variable defining the column structure - currently set to "q10_1_resp" - so that I only have to declare the local #cvar and use that in part 3 (like in part 4). I have succeeded in making part 3 into a sql-string with subsequent execution but then the column names stored in #sql1 cannot be used in the code in part 4 (I guess it is a scope thing).
--Part 1
create table [user].[test]
(rowvar nvarchar(max),
q10_1_resp int,
q10_2_resp int)
GO
INSERT [user].[test]
VALUES ('PH',1,2),
('PH',2,3),
('EA',1,5),
('EA',5,4),
('PH',3,4),
('PH',6,6),
('EA',4,1),
('PH',5,3),
('PH',2,1)
GO
-- Part 2
declare #rvar as nvarchar(max) = 'rowvar'
declare #cvar as nvarchar(max) = 'q10_1_resp' --this input should be dynamic as well
declare #sql1 as nvarchar(max)= ''
declare #sql2 as nvarchar(max)= ''
-- Part 3
select #sql1 = #sql1 + [a].[col] + char(44)
from
(select distinct QUOTENAME(q10_1_resp) as [col]
from [user].[test]
group by q10_1_resp) as a
SET #sql1 = left(#sql1, len(#sql1) - 1)
-- Part 4
SET #sql2 = 'select ' +
+ #rvar + ','
+ #sql1
+ ' from (Select '
+ #rvar + ', '
+ #cvar
+ ' from [user].[test]) sq pivot(count('
+ #cvar
+ ') for '
+ #cvar + ' IN ('
+ #sql1
+ ')) as pt'
exec sp_executesql #sql2
After a great deal of trying to globalize the scalarvariable without success using a temporary table to store the string was the key. The temporary table created at the beginning of the stored procedure can be assigned and referenced the entire time of the procedure. Thus assigning within execution of #sql and then referencing the string at execution of #sql2. I hope it makes sense.
CREATE PROCEDURE [dbo].[sp_crosstab]
-- Add the parameters for the stored procedure here
#rvar nvarchar(max) = '',
#cvar nvarchar(max) = '',
#data nvarchar(max) = '',
#sql nvarchar(max) = '',
#sql2 nvarchar(max) = '',
#sql3 nvarchar(max)=''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
create table #temp_crosstab
(
sqlstr nvarchar(max)
)
set #sql ='
declare #sql1 nvarchar(max) = char(00)
select #sql1 = #sql1 + [a].[col] + char(44)
from
(select distinct QUOTENAME(' + #cvar + ') as [col]
from ' + #data + '
group by ' + #cvar + ') as a
SET #sql1 = left(#sql1, len(#sql1) - 1)
insert into #temp_crosstab values (#sql1)'
execute sp_executesql #sql
select #sql3 = [sqlstr] from #temp_crosstab
set #sql2 = '
select ' + #rvar + char(44) +
#sql3 + 'from (Select '
+ #rvar + char(44) + ' '
+ #cvar
+ ' from ' + #data + ') sq pivot(count('
+ #cvar
+ ') for '
+ #cvar + ' IN ('+#sql3+')) as pt'
exec sp_executesql #sql2
END
GO
I'm trying to convert the following query to dynamic SQL to allow for variations:
UPDATE T
SET SumCount = J.SUM
FROM #temp T
JOIN (SELECT Count_99221 + COUNT_99222 + Count_99223 [SUM], t2.userID
FROM #temp t2
GROUP BY t2.userID, Count_99221 + COUNT_99222 + Count_99223
) J ON T.userID = J.UserID
This is what I have for the Dynamic SQL:
DECLARE #sql3 nvarchar(2000) =
'UPDATE T ' +
'SET SumCount = J.SumOfColumns ' +
'FROM #temp T ' +
'JOIN (SELECT ' + #columnSumString + ' [SumOfColumns], t2.userID ' +
'FROM #temp t2 ' +
'GROUP BY t2.userID, ' + #columnSumString +
' ) J ON T.userID = J.UserID'
EXEC sp_executesql #sql3
I am receiving the following error only when I run the query as Dynamic SQL:
Each GROUP BY expression must contain at least one column that is not
an outer reference.
Can somebody help explain why this is happening? I am new to Dynamic SQL so I'm not privy to any limitations for running queries this way.
Thank you in advance.
EDIT:
The variable #columnString is a string made by concatenating several other column names, created in the following way:
DECLARE #Cursor Cursor
DECLARE #code varchar(20)
DECLARE #ID INT
SET #cptCursor = CURSOR FOR
SELECT * FROM dbo.Split(#UserInput,CHAR(44))
OPEN #cptCursor
FETCH NEXT FROM #cptCursor INTO #ID, #code
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #colName varchar(50) = 'Count_' + cast(#code as varchar(10))
DECLARE #sql nvarchar(50) = 'ALTER TABLE #temp ADD ' + #colName + ' int'
EXEC sp_executesql #sql
--Code that adds values to each column that is created.....
SET #columnSumString = #colName + ' + ' + #columnSumString
--SET #columnSumString = #code + ' + ' + #columnSumString
FETCH NEXT FROM #cptCursor INTO #ID, #code
END
CLOSE #Cursor
DEALLOCATE #Cursor
SET #columnSumString = SUBSTRING(#columnSumString,1,LEN(#columnSumString)-2)
SELECT #columnSumString
The user input is a comma separated string. "Count_99221 + COUNT_99222 + Count_99223" is just one example of columns created from the user input "99221, 99222, 99223".
I also realized I was concatenating the #code variable into #columnSumString instead of #colName. Now when I run the query I don't get the error (even though I don't understand how the above error message relates to that mistake) but every value of SumCount is NULL.
IMHO you must re-write your query as follow:
UPDATE #temp
SET SumCount =
(SELECT Count_99221 + COUNT_99222 + Count_99223
FROM #temp t2
WHERE t2.userID = #temp.userID)
So the dynamic SQL will become:
DECLARE #columnString varchar(200)
SET #columnString = Count_99221 + COUNT_99222 + Count_99223
DECLARE #sql3 nvarchar(2000) =
N'UPDATE #temp ' +
'SET SumCount = (SELECT ' + #columnString +
' FROM #temp t2 WHERE t2.userID = #temp.userID)'
EXEC sp_executesql #sql3
I'm trying to call a stored procedure in SQL Server 2012 Express from a C# program, to insert a DateTime data type into a column (which is also datetime).
For some reason, I keep getting errors about "Conversation failed when converting date and/or time from character string."
I've checked the culture settings in my SQL server, which is set to us_english, but the datetime format is the ISO standard.
Here's the code from the stored procedure. The values are exactly how they're passed by the C# app.
USE testdb;
DECLARE #Name NVARCHAR(50) = 'Somename',
#Location NVARCHAR(50) = 'somelocation',
#Date DateTime = '2013-10-11 11:00:05.000'
BEGIN
SET NOCOUNT ON;
SELECT #Name, #Location, #Date
if exists (select name from ComputerHistory where name = #Name)
begin
DECLARE #Query1 NVARCHAR(MAX)
if #Location <> 'disconnected'
begin
set #Query1 = '
update ComputerHistory
set ' + #Location + ' = 1 + ISNULL((select MAX(' + #Location + ') from ComputerHistory where name = ''' + #Name + '''),0),
lastdateonline = ''' + #Date + '''
where name = ''' + #Name + '''
'
--EXEC sp_executesql #Query1
end
else
begin
set #Query1 = '
update ComputerHistory
set ' + #Location + ' = 1 + ISNULL((select MAX(' + #Location + ') from ComputerHistory where name = ''' + #Name + '''),0)
where name = ''' + #Name + '''
'
EXEC sp_executesql #Query1
end
end
else
begin
DECLARE #Query2 NVARCHAR(150)
set #Query2 = 'insert into ComputerHistory(name, ' + #Location + ') VALUES(''' + #Name + ''', ''1'')'
EXEC sp_executesql #Query2
end
END
Try cast(#Date as nvarchar(50))
set #Query1 = '
update ComputerHistory
set ' + #Location + ' = 1 + ISNULL((select MAX(' + #Location + ') from ComputerHistory where name = ''' + #Name + '''),0),
lastdateonline = ''' + cast(#Date as nvarchar(50)) + '''
where name = ''' + #Name + '''
'
The following code is supposed to take a string that may or may not be comma delimited and put it into a table (#tmpFullanme) that part works flawlessly. The second part is supposed return all the values that are LIKE / NOT LIKE with or without % symbols based on what is input. The error that I am getting is "the multi-part identifier "#tmpFullname.Item" could not be bound." The best guess I have is that it may be out of scope?
DROP PROCEDURE uspJudgments;
GO
CREATE PROCEDURE uspJudgments
#fullName varchar(100), #SrchCriteria1 varchar(15), #SrchCriteria2 varchar(15), #qualifier varchar(10)
AS
BEGIN
SELECT *
INTO #tmpFullname
FROM dbo.DelimitedSplit8K(#fullName, ',')
DECLARE #Query NVarChar(1024)
SET #Query = 'SELECT d.*' + ' FROM defendants_ALL d, #tmpFullname' +
' WHERE d.combined_name' + ' ' + #qualifier + ' ' + '''' + #SrchCriteria1 + '''' + ' + ' + '''' + #tmpFullname.Item + '''' + ' + ' + '''' + #SrchCriteria2 + ''''
END
EXEC sp_executesql #Query
PRINT(#Query)
IF OBJECT_ID('#tmpFullname', 'U') IS NOT NULL
DROP TABLE #tmpFullname
EXEC uspJudgments #qualifier = 'LIKE', #fullName = 'johnson', #SrchCriteria1 = '%', #SrchCriteria2 = '%'
Cannot get to the PRINT output as "the multi-part identifier "#tmpFullname.Item" could not be bound." If I change #tmpFullname.Item to '#tmpFullname.Item it goes through and returns nothing but it shows that the query is correct minus the issue with that table.
SELECT d.* FROM defendants_ALL d, #tmpFullname WHERE d.combined_name LIKE '%' + '#tmpFullname.Item' + '%'
Please note that until I made this into a dynamic query so I can change the statement from LIKE to IN etc it worked very well.
I set up a full test to get the proper script to get you your desired results. I also have a SQL Fiddle showing how this works. Note You will want to run EXECUTE sp_executesql #Query inside the stored procedure
ALTER PROCEDURE uspJudgments #fullName varchar(100)
, #SrchCriteria1 varchar(15)
, #SrchCriteria2 varchar(15)
, #qualifier varchar(10)
AS
BEGIN
--Simulates your split function
SELECT *
INTO #tmpFullName
FROM
(
SELECT 'firstTest' AS Item
UNION ALL SELECT 'secondTest'
UNION ALL SELECT 'NotThere'
) AS t;
DECLARE #Query NVARCHAR(1024);
SELECT #Query = 'SELECT d.* '
+ ' FROM defendants_ALL d '
+ ' CROSS JOIN #tmpFullName AS t '
+ ' WHERE d.combined_name' + ' ' + #qualifier + ' '
+ '''' + #SrchCriteria1 + ''''
+ ' + ' + 't.Item' + ' + ' + '''' + #SrchCriteria2 + '''';
EXECUTE sp_executesql #Query;
END
EXECUTE uspJudgments
#fullName = 'does not matter'
, #SrchCriteria1 = '%'
, #SrchCriteria2 = '%'
, #qualifier = 'LIKE';
You have to use the tempdb prefix in this case
insert into tempdb..#TABLENAME
and
set #query = 'select * from tempdb..#TABLENAME'
Well, After my last answer i have found several things..
When i look into your procedure you start with the "BEGIN", next you do a insert into the "#tmpFullName" table, your declare the "#Query" variable and create a select statement.
After that you do and "END" with logic after it. You do the "sp_executesql" after that you drop the temptable and you do and EXEC of the current procedure..
The Structure isn't all that readable, sorry to tell you. So maybe you go there first.
Beside a strange structure you are using the "#tmpFullName.Item" in some dynamic SQL as a parameter, while it is declared inside the SQL query it self. So you have to do something like this :
SET #Query = 'SELECT d.*' + ' FROM defendants_ALL d, #tmpFullname' +
' WHERE d.combined_name' + ' ' + #qualifier + ' ' + '''' + #SrchCriteria1 + '''' + ' + ' + ' #tmpFullname.Item ' + ' + ' + '''' + #SrchCriteria2 + ''''
Where the "#tmpFullName.Item" resides insde the code, not as a parameter. But then again, what are you trying to achieve here? To answer this completly we have to know what the other variables are. Your structure isn't telling me what are trying to achieve..
I really can't make any more out of it...
I have the following dynamic sql statement where I want to add #StartRowIndex + #MaximumRows and subtract 1 from it. I am unclear on where to put the single quotes in the statement. Here it is:
SET #sql = #sql + ' SELECT *
FROM
LicenseInfo
WHERE RowNum
BETWEEN ' + #StartRowIndex + ' AND ' +
'(' + #StartRowIndex + #MaximumRows + ')' - 1
+ ' ORDER BY cnt desc'
Create new variable #EndRowIndex and calculate it before you construct the dynamic sql statement.
Something like:
DECLARE #EndRowIndex int
SET #EndRowIndex = #StartRowIndex + #MaximumRows - 1
SET #sql = #sql + ' SELECT *
FROM
LicenseInfo
WHERE RowNum
BETWEEN ' + #StartRowIndex + ' AND ' + #EndRowIndex
+ ' ORDER BY cnt desc'
You need to cast the int parameters into varchar
SET #sql = #sql + ' SELECT *
FROM
LicenseInfo
WHERE RowNum
BETWEEN ' + #StartRowIndex + ' AND ' +
'(' + CAST(#StartRowIndex as varchar(10)) + CAST(#MaximumRows as varchar(10)) + ') - 1
ORDER BY cnt desc'
Declare a variable, do the calculation and CAST it to varchar when generating the SQL statement
DECLARE #LastRowIndex int
SET #LastRowIndex = #StartRowIndex + #MaximumRows - 1
SET #sql = #sql + '
SELECT *
FROM LicenseInfo
WHERE 1=1
AND RowNum BETWEEN ' + CAST (#StartRowIndex as VarChar) +
' AND ' + CAST (#LastRowIndex as VarChar)
+ ' ORDER BY cnt DESC'
You have to cast in order to let SQL Server concatenate string values, otherwise it will try to convert the nVarChar to number and try to add them as numerics.