I'm getting an error
Must declare the scalar variable "@model_look_xml"
when creating a dynamic query.
This executes fine:
SELECT *
FROM model
WHERE (model_height BETWEEN 0.00 AND 80.00
AND model_id IN (SELECT DISTINCT assn.assn_model_id
FROM model_look
INNER JOIN model_skill ON model_look.model_look_model_id =
model_skill.model_skill_model_id
INNER JOIN assn ON assn.assn_model_id = model_skill.model_skill_model_id
WHERE assn.assn_office = 34
AND model_skill_skill_id = 12
AND EXISTS (SELECT 1
FROM @model_look_xml.nodes('/root/id') AS result(node)
WHERE node.value('(.)[1]', 'int') = model_look_look_id))
When I try to break it up dynamically, I'm not sure how to handle the nodes.
This works fine:
declare @model_look_xml xml
declare @model_skill_xml xml
declare @model_eyes_xml xml
declare @model_hair_xml xml
declare @model_ethnicity_xml xml
declare @model_skill_skill_id int
declare @assn_office int
declare @top_height decimal(4,2)
declare @low_height decimal(4,2)
declare @SQL NVARCHAR(MAX)
--testing values
set @assn_office = 34
set @top_height = 80.00
set @low_height = 0.00
set @model_look_xml = CAST('<root><id>7</id><id>6</id><id>12</id></root>' AS XML)
SET @SQL = N'SELECT * FROM model where '
SET @SQL = @SQL + N'(model_height between '
SET @SQL = @SQL + cast(@low_height as varchar(50))
SET @SQL = @SQL + ' and '
SET @SQL = @SQL + cast(@top_height as varchar(50))
SET @SQL = @SQL + N' and model_id in (Select distinct assn.assn_model_id From '
SET @SQL = @SQL + N'model_look Inner Join
model_skill On model_look.model_look_model_id =
model_skill.model_skill_model_id Inner Join
assn On assn.assn_model_id = model_skill.model_skill_model_id
Where assn.assn_office = '+ cast(@assn_office as varchar(50)) +'
and model_skill_skill_id = '+ cast(@model_skill_skill_id as varchar(50) ) --+'))'
SET @SQL = @SQL + N' and exists(select 1 from '
Until I get to this line, not sure how to handle it. If I was only going to do this once I would have found a different way, but I'm going to have 6 optional parameters(possible lists) coming in.
SET @SQL = @SQL + N'@model_look_xml.nodes(''/root/id'')as result(node) where node.value(''(.)[1]'', ''int'') = model_look_look_id))'
Aucun commentaire:
Enregistrer un commentaire